<?php
class cronController extends base
{
    public function __construct()
    {
        parent::__construct('default');
    }
    /**
     * 保存当天pm25数据
     */
    public function dosavePm25()
    {
        $url = 'http://www.pm25.in/api/querys/aqi_ranking.json';
        $data = common::getContents($url, array('token'=> 'rTkDqyKkvsSJrPPLpV2K'));
        $data = json_decode($data, TRUE);

        $insertArr = array();

        if(empty($data)){
            $this->result['result'] =  '数据为空';
        }
        foreach ($data as $val)
        {
            $city = $val['area'] . '市';
            $city_id = $this->db->getOne("select city_id from r_city where city='{$city}'");
            $t = strtotime($val['time_point']);

            //保存pm2.5数据
            if($city_id){
                $v['city_id'] = $city_id;
                $v['pm25'] = $val['pm2_5'];
                $v['pm25_24'] = $val['pm2_5_24h'];
                $v['quality'] = $val['quality'];
                $v['level'] = $val['level'];
                $v['update_time'] = strtotime($val['time_point']);
                $this->load('pm25')->insertPm25($v);
            }
        }

        echo date('Y-m-d H:i:s').'保存天气成功。';
        exit();
    }
    /**
     * 保存城市天气数据 版本：大于1.1.0
     */
    public function doupdateWeather()
    {
        set_time_limit(180);
        $redis_need_up_key = REDIS_PREFIX . 'update';
        $cityList = $this->redis->smembers($redis_need_up_key);
        if(empty($cityList))
        {
            echo date('Y-m-d H:i:s').'需更新天气的城市列表为空'."\n";
            exit();
        }
        else
        {
            foreach ($cityList as $key => $city_id)
            {
                if(!empty($city_id))
                {
                    $weather = $this->load('weather')->getWeather($city_id);
                    if(empty($weather))
                    {
                        echo date('Y-m-d H:i:s').'获取天气信息失败。'."\n";
                        exit();
                    }
                    $this->load('weather')->insertWeather($weather);
                }
            }
            echo date('Y-m-d H:i:s').'更新天气成功。'."\n";
            exit();
        }
    }
    /**
     * 更新所有城市天气信息
     */
    public function doupdateAllWeather()
    {
        $allcity = $this->load('weather')->getAllCity();
        if($allcity)
        {
            set_time_limit(540);
            foreach($allcity as $city)
            {
                $city_id = $city['city_id'];
                $weatherData = $this->load('weather')->getWeather($city_id);
                $this->load('weather')->insertWeather($weatherData);
            }
            echo date('Y-m-d H:i:s').'天气更新完成'."\n";
            exit();
        }
        else
        {
            echo date('Y-m-d H:i:s').'城市列表为空'."\n";
            exit();
        }
    }
    /*
     * 消息推送
     */
    public function doPushMessage()
    {
        ini_set('memory_limit', '4096M');

		$time= time();
        $lock = $this->db->getRowTable('r_msg_push', array('msg_id'), "status = 1");
        if($lock){
            echo '上一条执行中';
            exit;
        }
        $message = $this->db->getRowTable('r_msg_push', array(), "status != '2' and send_time <= {$time}", 'add_time ASC');
        if(!empty($message))
        {
            $status = $this->load('push')->goPushMessage($message);
            echo date('Y-m-d H:i:s');
            echo $status == 2 ? '推送任务完成。-' : '推送任务进行中。-';
            echo $message['msg_id']."-\n";
            exit();
        }
        else
        {
            $this->load('news')->timerShowNews();
            echo date('Y-m-d H:i:s').'推送任务列表为空'."\n";
            exit();
        }
    }
    /*
     * 统计 通知消息未送达 的全部 device_id/token
     */
    public function dogetPushFailedDevice()
    {
        $result = $this->load('push')->getFailedClient();
        echo date('Y-m-d H:i:s').'完成'."\n";
        echo '安卓：'.$result['client'].','.'IOS 失败：'.$result['token'].','.'IOS 无效：'.$result['Invalidtokens']."\n";
        exit;
    }
    /*
     * 保存资讯点击统计数据
     */
    public function dosaveNewsClickStat()
    {
        $this->load('news')->saveNewsClickData();
        echo date('Y-m-d H:i:s').' 保存资讯点击统计数据完成'."\n";
        exit;
    }
    /*
     * 标记游客跑步数据是否已被上传到相应设备的user下
     */
    public function domarkVisitorRun()
    {
        $start = common::request("start", 'G', 0);
        $this->load('run')->markVisitorRunData($start);
        echo date('Y-m-d H:i:s').' 标记完成'."\n";
        exit;
    }
    /*
     * 更新设备最后访问时间
    */
    public function doupdateLastVisit()
    {
        $redisKey = REDIS_PREFIX.'CidVisit';
        $time = time();
        while ($this->redis->ZCOUNT($redisKey, 0, $time) > 0) {
            $data = $this->redis->ZREVRANGEBYSCORE($redisKey, $time, 0, array('withscores' =>TRUE));
            foreach ($data as $cid => $time) {
                $this->db->query("update r_client set last_visit = '{$time}' where cid = '{$cid}'");
                $this->redis->ZREM($redisKey, $cid);
            }
        }
        echo date('Y-m-d H:i:s').'更新设备最后访问时间'."\n";
        exit;
    }
    /*
     * 更新社区首页热门帖子
    */
    public function doupdateBbsHotPost()
    {
        $this->load('bbs')->updateTopHotPost();
        $this->load('bbs')->updateHomeBestPost();
        echo date('Y-m-d H:i:s').'更新社区首页热门帖子'."\n";
        exit;
    }

    /**
     * 广播消息
     * @return [type] [description]
     */
    public function doBroadcast(){
        $rst = $this->load('message')->getBroadcastMessage();
        foreach ($rst as $key => $value) {
            $fromUserId = 'S10004';//扑妞账户
            $objectName = 'RC:TxtMsg';//文本
            $content = $value['content'];
            $pushContent = '';
            $pushData = 'pushd';
            $this->load('message')->messageBroadcast($fromUserId, $objectName, $content, $pushContent, $pushData);
        }
    }

    /**
     * 消息历史纪录下载
     * @return [type] [description]
     */
    public function doMessageHistory()
    {
        $date_ymd = date("Ymd",strtotime("-1 day"));
        for($i = 1; $i <= 24; $i++)
        {
            //$date = common::request("date", 'G', 0);
            $date = $date_ymd . sprintf("%02d", $i);
            $rst = $this->load('message')->messageHistory($date);//2015042215
            if(!empty($rst['url'])){
                $this->download($rst['url'], $date);
            }

        }
    }


    /**
     * 同步用户所属群组 方法
     * @return [type] [description]
     */
    public function doGroupSync()
    {
        $allUserCount = $this->load('client')->getAllUserCount();
        $rows = 10;
        $length = ceil($allUserCount / $rows);
        for($i = 0; $i < $length; $i++) {

            $offset = $rows * $i;
            //获取所有用户
            $allUser = $this->load('client')->getAllUser($offset,$rows);

            foreach ($allUser as $key => $item) {
                //获取这个用户所加入的群组集合
                $allGroup = $this->load('group')->getGroupsByUid($item['uid']);
                $groupsInfo = array();
                foreach ($allGroup as $key => $value) {
                    $groupsInfo[$value['gid']] = $value['name'];
                }

                $userId = $item['uid'];//用户ID
                $data = $groupsInfo;//群组信息

                if(!empty($data)){
                    $this->load('message')->groupSync($userId,$data);
                }

            }
        }
    }

    /**
     * 任务发送通知消息
     * @return [type] [description]
     */
    public function doSendMsg()
    {
        $all = $this->load('message')->findAllMessageByIsSend();
        foreach ($all as $key => $value) {
            switch ($value['category']) {
                case '1':
                    //新的朋友
                    $this->sendFriendMsg($value);
                    break;
                case '2':
                    //有道帖子
                    $this->sendNewsMsg($value);
                    break;
                case '3':
                    //群消息
                    $this->sendGroupMsg($value);
                    break;
            }
        }
    }
    public function sendFriendMsg($data)
    {
        $fromUserId = $data['send_id'];//新的朋友、跑步有道、群组账户
        $toUserId = array($data['target_id']);
        $objectName = "RC:TxtMsg";
        $extra = base64_encode(json_encode($this->load('message')->convertFriendMessageContent($data)));
        $content = '{"content":"","extra":"'.$extra.'"}';
        $pushContent = "";
        $pushData = "1";
        $rst = $this->sendRongCloud($fromUserId, $toUserId, $objectName, $content, $pushContent, $pushData);
        if($rst){
            $this->updateMessage($data['id']);
        }
    }

    public function sendNewsMsg($data)
    {

        $fromUserId = $data['send_id'];
        $toUserId = array($data['target_id']);
        $objectName = "RC:TxtMsg";
        $extra = base64_encode(json_encode($this->load('message')->convertNewsMessageContent($data)));
        $content = '{"content":"","extra":"'.$extra.'"}';
        $pushContent = "";
        $pushData = "1";

        $rst = $this->sendRongCloud($fromUserId, $toUserId, $objectName, $content, $pushContent, $pushData);
        if($rst){
            $this->updateMessage($data['id']);
        }
    }

    public function sendGroupMsg($data)
    {
        $fromUserId = $data['send_id'];
        $toUserId = array($data['target_id']);
        $objectName = "RC:TxtMsg";
        $extra = base64_encode(json_encode($this->load('message')->convertGroupMessageContent($data)));
        $content = '{"content":"","extra":"'.$extra.'"}';
        $pushContent = "";
        $pushData = "1";
        $rst = $this->sendRongCloud($fromUserId, $toUserId, $objectName, $content, $pushContent, $pushData);
        if($rst){
            $this->updateMessage($data['id']);
        }
    }

    /**
     * 更新消息状态
     * @param  [type] $mId [description]
     * @return [type]      [description]
     */
    private function updateMessage($id)
    {

        $is_send = 1;
        $array = compact('id','is_send');

        $rst = $this->db->updateRowTable('r_message_record', $array);
    }

    public function sendRongCloud($fromUserId, $toUserId, $objectName, $content, $pushContent, $pushData){
        return $this->load('message')->messageSystemPublish($fromUserId, $toUserId, $objectName, $content, $pushContent, $pushData);
    }

    /**
     * 注册IM的用户、群组
     * @return [type] [description]
     */
    public function doImRegister()
    {
        $start_time = time();
        if(TRUE){
            //获取im_token为空用户;
            $userInfo = $this->getUserInfoByIsNull();

            foreach ($userInfo as $key => $value) {
                $id = $value['uid'];
                $nickname = $value['nickname'];
                $header = !empty($value['header']) ? $value['header'] : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png";
                //注册token IM
                $rst = $this->getToken($id,$nickname,$header);
                if($rst['code'] == 200){
                    //添加对应用户的im_token的值
                    $this->updateUserInfoImToken($value['uid'],$rst['token']);
                }else{
                    //获取token失败日志
                    $this->userGetTokenLog($id, $nickname, $header, '', false, $rst);
                }

                if($start_time - time() >= 50){
                    echo date('Y-m-d H:i:s') . "同步用户im_token 暂停";
                    exit();
                }
            }
            //获取所有群组
            $groupInfo = $this->getAllGroupInfo();
            foreach ($groupInfo as $key => $value) {
                $groupId = $value['gid'];
                $groupName = $value['name'];
                //创建群组IM
                $rst = $this->groupCreate($value['uid'],$groupId,$groupName);
                if($rst['code'] == 200){
                    //更新群组同步状态
                    $this->updateGroupStatus($groupId);
                    //群组创建成功日志
                    $this->groupCreateLog($value['uid'],$groupId,$groupName);
                    //获取群组中所有的用户
                    $gUserInfo = $this->getUserInfoByGroupId($groupId);
                    foreach ($gUserInfo as $gKey => $gValue) {
                        //将用户加入群组
                        $rst = $this->groupJoinByUser($gValue['uid'],$groupId,$groupName);
                        if($rst['code'] == 200){
                            //加入群组成功日志
                            $this->groupJoinLog($groupId,$groupName,$gValue['uid']);
                        }else{
                            //加入群组失败日志
                            $this->groupJoinLog($groupId,$groupName,$gValue['uid'],false);
                        }
                    }
                }else{
                    //群组创建失败日志
                    $this->groupCreateLog($value['uid'],$groupId,$groupName,false);
                }
                if($start_time - time() >= 50){
                    echo date('Y-m-d H:i:s') . "同步群组数据 暂停";
                    exit();
                }
            }

            echo date('Y-m-d H:i:s') . "同步完成";
        }
    }


    /**
     * 获取所有im_token为空的用户
     *
     * @return [type] [description]
     */
    public function getUserInfoByIsNull(){
        return $this->load('user')->getUserInfoByIMTokenIsNull();
    }

    /**
     * 获取IM的用户token
     *
     * @param  [type] $id       [description]
     * @param  [type] $nickname [description]
     * @param  [type] $header   [description]
     * @return [type]           [description]
     */
    public function getToken($id,$nickname,$header){
        return $this->load('message')->getToken($id,$nickname,$header);
    }

    /**
     * 更新用户的im_token
     * @param  [type] $id    [description]
     * @param  [type] $token [description]
     * @return [type]        [description]
     */
    public function updateUserInfoImToken($id,$token){
        return $this->load('user')->updateUserInfo($id,$token);
    }

    /**
     * 获取所有群信息
     * @return [type] [description]
     */
    public function getAllGroupInfo(){
        return $this->load('group')->getAllGroupInfo();
    }

    /**
     * 更新群组同步状态
     * @param  [type] $gid [description]
     * @return [type]      [description]
     */
    public function updateGroupStatus($gid){
        return $this->load('group')->updateGroupStatus($gid);
    }

    /**
     * 根据群ID 获取用户信息
     * @param  [type] $groupId [description]
     * @return [type]          [description]
     */
    public function getUserInfoByGroupId($groupId){
        return $this->load('group')->getUserInfoByGroupId($groupId);
    }

    /**
     * 创建群组
     * @param  [type] $createrId [description]
     * @param  [type] $groupId   [description]
     * @param  [type] $groupName [description]
     * @return [type]            [description]
     */
    public function groupCreate($createrId,$groupId,$groupName){
        return $this->load('message')->groupCreate($createrId, $groupId, $groupName);
    }

    /**
     * IM 加入群组
     * @param  [type] $uid       [description]
     * @param  [type] $groupId   [description]
     * @param  [type] $groupName [description]
     * @return [type]            [description]
     */
    public function groupJoinByUser($uid, $groupId, $groupName){
        return $this->load('message')->groupJoin($uid, $groupId, $groupName);
    }

    /**
     * IM 加入群组的日志记录
     * @param  [type]  $uid       [description]
     * @param  [type]  $groupId   [description]
     * @param  [type]  $groupName [description]
     * @param  boolean $is_suc    [description]
     * @return [type]             [description]
     */
    public function groupJoinLog($uid, $groupId, $groupName, $is_suc = true){
        $log_content = '['.date("Y-m-d H:i:s").']';
        if($is_suc){
            $log_content .= "groupId=" . $groupId . ";groupName=" . $groupName . ";uid=" . $uid . ";加入群组成功";
        }else{
            $log_content .= "groupId=" . $groupId . ";groupName=" . $groupName . ";uid=" . $uid . ";加入群组失败";
        }
        $log_content .= "\n";
        $this->loginfo($log_content,'register_group','im');
    }

    /**
     * IM 群组创建的日志记录
     * @param  [type]  $uid       [description]
     * @param  [type]  $groupId   [description]
     * @param  [type]  $groupName [description]
     * @param  boolean $is_suc    [description]
     * @return [type]             [description]
     */
    public function groupCreateLog($uid, $groupId, $groupName, $is_suc = true){
        $log_content = '['.date("Y-m-d H:i:s").']';
        if($is_suc){
            $log_content .= "groupId=" . $groupId . ";groupName=" . $groupName . ";creater=" . $uid . ";创建群组成功";
        }else{
            $log_content .= "groupId=" . $groupId . ";groupName=" . $groupName . ";creater=" . $uid . ";创建群组失败";
        }
        $log_content .= "\n";
        $this->loginfo($log_content,'register_group','im');
    }

    /**
     * IM用户获取 获取token的日志记录
     * @param  [type]  $uid      [description]
     * @param  [type]  $nickname [description]
     * @param  [type]  $header   [description]
     * @param  [type]  $token    [description]
     * @param  boolean $is_suc   [description]
     * @return [type]            [description]
     */
    public function userGetTokenLog($uid, $nickname, $header, $token, $is_suc = true, $rst)
    {
        $log_content = '['.date("Y-m-d H:i:s").']';
        $rst = is_array($rst) ? urldecode(http_build_query($rst, NULL, '&')) : $rst;
        $rst .=  "\n";
        if($is_suc){
            $log_content .= "uid=" . $uid . ";nickname=" . $nickname . ";header=" . $header . ";token=" . $token . ";获取token成功". $rst;
        }else{
            $log_content .= "uid=" . $uid . ";nickname=" . $nickname . ";header=" . $header . ";获取token失败" . $rst;

        }
        $log_content .= "\n";
        $this->loginfo($log_content,'register_user','im');
    }



    /**
     * 记录日志
     * @param  [type] $fileName [description]
     * @param  [type] $content  [description]
     * @return [type]           [description]
     */
    private function loginfo($content, $fileName = 'log', $folder = 'default'){
        //文件所处目录
        $path = $this->config['log-dir'] . $folder . "/";
        //查看文件目录是否存在,不存在创建
        !file_exists($path) && mkdir($path);
        //文件名称及类型
        $logName = $fileName.'.txt';
        //写入方式打开，将文件指针指向文件末尾。如果文件不存在则尝试创建之。
        $fp = fopen($path.$logName, "a");
        //写入内容
        fwrite($fp, $content);
        //写入换行
        fwrite($fp, "\n");
        //关闭
        fclose($fp);
    }

    /**
     * 下载文件目录设置
     * @param  [type] $fileUrl [description]
     * @param  [type] $date    [description]
     * @return [type]          [description]
     */
    private function download($fileUrl,$date){
        $dest_folder = $this->config['log-dir'] . 'message-log/' . $date . '/';
        //文件目录是否存在
        if(!file_exists($dest_folder)){
            //建立目录
            mkdir($dest_folder, 0777, true);
        }
        //新文件(包括文件名和文件目录)
        $dir=$dest_folder . basename($fileUrl);
        $contents = $this->server_download($fileUrl,$dir);

    }

    /**
     * 下载文件
     * @param  [type] $url [description]
     * @param  [type] $dir [description]
     * @return [type]      [description]
     */
    function server_download($url, $dir) {
        $ch = curl_init($url);
        $fp = fopen($dir, "wb");
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $res=curl_exec($ch);
        curl_close($ch);
        fclose($fp);
        return $res;
    }
    /**
     * 向PPTV发送跑步数据
     */
    public function dosendPPTVRunData()
    {
        $time = $this->time;
        $data = $this->redis->ZRANGEBYSCORE(REDIS_PREFIX.'PPTVSend', 0, $time);
        if(empty($data))
        {
            echo date('Y-m-d H:i:s') . '无待发送数据' . "\n";
            exit();
        }
        echo date('Y-m-d H:i:s').'待发送数据' . var_export($data,true) . "\n";
        foreach ($data as $v) {
            $sendData = $this->redis->hget(REDIS_PREFIX.'PPTVRunData', $v);
            $sendData = @json_decode($sendData, TRUE);
            if(!is_array($sendData) || !isset($sendData['runUserId']) || !isset($sendData['pptvUserId']) || !isset($sendData['runData']))
            {
                continue;
            }
            extract($sendData);
            if(!isset($times))
                $times = 0 ;
            $runUserId = $sendData['runUserId'];
            $pptvUserId = $sendData['pptvUserId'];
            $runData = $sendData['runData'];
            echo date('Y-m-d H:i:s').'详细数据' . var_export($sendData,true) . "\n";
            echo date('Y-m-d H:i:s').'详细数据runUserId=' . $runUserId . "\n";
            echo date('Y-m-d H:i:s').'详细数据pptvUserId=' . $pptvUserId . "\n";
            echo date('Y-m-d H:i:s').'详细数据runUserId=' . var_export($runData,true) . "\n";
            $rel = $this->load('partner')->sendRunData('PPTV', $runUserId, $pptvUserId, $runData);
            echo date('Y-m-d H:i:s').'返回值' . $rel . "\n";
            $rel = intval($rel);
            echo date('Y-m-d H:i:s').'返回值=' . $rel . "\n";
            switch ($rel) {
                case 2:
                    $this->redis->ZREM(REDIS_PREFIX.'PPTVSend', $v);
                    $this->redis->hdel(REDIS_PREFIX.'PPTVRunData', $v);
                    $this->load('partner')->unbind('PPTV', $runUserId, $pptvUserId);
                    break;
                case 1:
                    $this->redis->ZREM(REDIS_PREFIX.'PPTVSend', $v);
                    $this->redis->hdel(REDIS_PREFIX.'PPTVRunData', $v);
                    break;
                case 0:
                    if($times == 0)
                    {
                        $this->redis->ZADD(REDIS_PREFIX.'PPTVSend', $time+1800, $v);
                    }
                    else if($times == 1)
                    {
                        $this->redis->ZADD(REDIS_PREFIX.'PPTVSend', $time+7200, $v);
                    }
                    else
                    {
                        $this->redis->ZREM(REDIS_PREFIX.'PPTVSend', $v);
                        $this->redis->hdel(REDIS_PREFIX.'PPTVRunData', $v);
                    }
                    break;
                default:
                    $this->redis->ZREM(REDIS_PREFIX.'PPTVSend', $v);
                    $this->redis->hdel(REDIS_PREFIX.'PPTVRunData', $v);
                    break;
            }
        }
        echo date('Y-m-d H:i:s')."向PPTV发送跑步数据结束\n";
        exit();
    }
    /**
     * 更新用户排行榜
     */
    public function dogetMileageStandingsRank()
    {
        $this->load('run')->updateMileageStandingsInfo();
        echo date('Y-m-d H:i:s')."更新用户排行榜\n";
        exit();
    }

    /**
     *  重新发送 QQ健康数据发送失败的数据
     */
    public function doresendQqHealthFail()
    {
        $startTime = time();

        $this->load('run');
        do
        {
            $rel = $_ENV['run']->resendQqHealthData();
            if($rel === FALSE)
            {
                break;
            }
            $timeUsed = time() - $startTime;
        }
        while ($timeUsed <= 55);

        echo date('Y-m-d H:i:s')."  重新发送 QQ健康数据发送失败的数据\n";
        exit();
    }
    /**
     *  跑步数据保存成功后的后续处理
     */
    public function dodisposeRunData()
    {
        echo date('Y-m-d H:i:s') , " | start\n";

        $start = time();
        $partner_mod = $this->load('alibaba');

        do{
            $did = $this->load('run')->popPendingRunData();
            echo date('Y-m-d H:i:s') , " | did: {$did} begin\n";
            if(!empty($did))
            {
                $runData = $this->db->getRow('select * from r_data left join r_data_ext on r_data_ext.did=r_data.did where r_data.did='.$did.' limit 1');

                if(!empty($runData))
                {
                    //获取版本号
                    $version = $this->load('client')->getVersionByCid($runData['cid']);
                    // 群组跑步数据
                    if($version >= 2200)
                    {
                        // 更新用户最近跑步记录
                        $runRecord = array('did' => $did,
                            'mileage'        => $runData['mileage'],
                            'elapsedtime'    => $runData['elapsedtime'],
                            'city'           => $runData['city'],
                            'calorie'        => $runData['calorie'],
                            'updatetime'     => $runData['updatetime'],
                            'five_time'     => $runData['five_time'],
                            'ten_time'     => $runData['ten_time'],
                            'half_mtime'     => $runData['half_mtime'],
                            'mara_time'     => $runData['mara_time']
                        );
                        if($runData['overSpeed'] == 0)
                        {
                            $this->load('group')->addGroupRunData($runData['uid'],$runRecord);
                        }
                    }

                    $qqInfo = $this->load('run')->getQqHealthInfo($did);

                    // 数据发给(QQ健康中心)
                    if(isset($qqInfo['token']) && !empty($qqInfo['token']) && isset($qqInfo['token']) &&  !empty($qqInfo['openid']))
                    {
                        $qqHealthData = array('access_token' => $qqInfo['token'],
                            'openid'       => $qqInfo['openid'],
                            'uid'          => $runData['uid'],
                            'time'         => $runData['updatetime']
                        );
                        $rel = $this->load('run')->sendQqHealthData($qqHealthData);

                        if(preg_match('/^{"ret":-56,/', $rel) || preg_match('/^{"ret":-69,/', $rel))
                        {
                            $_ENV['run']->qqHealthFail($qqHealthData);
                        }
                    }
                    
                    // 数据发送给阿里体育
                    if(!$runData['overSpeed'] && $runData['coordinate']){
                        $coordinate = $runData['coordinate'];
                        $runData['coordinate'] = json_decode(gzuncompress(base64_decode($coordinate)),true);
                        $partner_mod->addData($runData);
                    }
                }
            }
            else
            {
                sleep(3);
            }
            echo date('Y-m-d H:i:s') , " | did: {$did} end\n";
            $end = time();
           $useTime = $end-$start;
       }while($useTime <= 55);

       echo date('Y-m-d H:i:s') , " | stop\n\n";
    }
    /**
     *  更新微信网页授权的 component_access_token
     */
    public function dowxcomponentToken()
    {
        $token = $this->load('weixin')->updateComponentAcsToken();

        echo date('Y-m-d H:i:s')."更新component_access_token： $token\n";
        exit();
    }

    private function _getTime(){
        list($s1, $s2) = explode(' ', microtime());
        return sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
    }

    public function backup()
    {
        $start = $this->_getTime();
     //   do{
            $did = $this->load('run')->popPendingRunData();
            $end = $this->_getTime();
            $useTime = $end-$start;
            $runData = $this->db->getRow('select * from r_data where did='.$did.' limit 1');
           // $this->load('run')->uploadUserRunData($runData);

            //******RunData************
              // 更新用户最近跑步记录
                  $runRecord = array('did' => $did,
                      'mileage'        => $runData['mileage'],
                      'elapsedtime'    => $runData['elapsedtime'],
                      'city'           => $runData['city'],
                      'calorie'        => $runData['calorie'],
                      'updatetime'     => $runData['updatetime'],
                      'five_time'     => $runData['five_time'],
                      'ten_time'     => $runData['ten_time'],
                      'half_mtime'     => $runData['half_mtime'],
                      'mara_time'     => $runData['mara_time']
                    );
                 if($runData['overSpeed'] == 0)
                  {
                      $this->load('group')->addGroupRunData($uid,$runRecord);
                  }
            $useTime = $end-$start;
      //  }while($useTime <= 5500);

    }
    
    /**
     * 帖子增加imginfo属性的值
     */
    public function dotransfer(){
        $info = $this->db->getAll("select news_id,sourceImg from r_news where imginfo='' limit 500");
        echo "======start======";
        while(!empty($info)){

            foreach($info as $val){
                $imgs = json_decode($val['sourceImg'],true);
                $id = $val['news_id'];
                $imginfo = array();
                for($i=0;$i<count($imgs);$i++){
                    if(isset($imgs[$i])){
                        $item = @getimagesize($imgs[$i]);
                        $imginfo[$i]['width'] = isset($item[0]) ? $item[0] : 450;
                        $imginfo[$i]['height'] = isset($item[1]) ? $item[1] : 450;
                    }
                }
                $imginfo = json_encode($imginfo);
                $this->db->query("update r_news set imginfo='{$imginfo}' where news_id=$id");

                $this->redis->delete(REDIS_PREFIX. "NewsInfo_{$id}");
                $info = $this->db->getAll("select news_id,sourceImg from r_news where imginfo='' limit 500");
            }
        }
        echo "======end======";

    }

    public function doclearLog()
    {
        $time = strtotime('-1 month');
        $this->logDB->query("DELETE FROM client_odd WHERE create_day < $time");
    }
    
    //取消活动并发送通知
    public function doafterGroupDismiss(){
        echo '=======start=======';
        if(intval($this->redis->get(REDIS_PREFIX."ActFlag")) == 1){
            return;
        }
        
        $gid = $this->redis->rpop(REDIS_PREFIX.'GroupDismiss');
        if(!$gid){
            return;
        }
        $group_mod = $this->load('group');
        $group_activity_mod = $this->load('groupActivity');
        $gInfo = $group_mod->getGroupInfo($gid);
        if(empty($gInfo)){
            return;
        }
        $result = $this->load('groupActivity')->getIngAct($gid,0,1);
        $aids = $this->redis->zRangeByScore(REDIS_PREFIX."GroupActivity_".$gid,2,'+inf');
        $flag = false;
        foreach($aids as $aid){
            if($this->redis->sIsMember(REDIS_PREFIX."ACTaccept_".$aid,$gid)){
                $stime = $this->redis->hget(REDIS_PREFIX."ActivityInfo_".$aid,'stime');
                $etime = $this->redis->hget(REDIS_PREFIX."ActivityInfo_".$aid,'etime');
                if(time() >= $stime && $etime >= time()){
                    $flag = true;
                    break;
                }
            }
        }
        //没有进行中活动
        if(!$result && !$flag){
            return;
        }
        $group_activity_mod = $this->load('groupActivity');
        $this->redis->set(REDIS_PREFIX."ActFlag",1);
        foreach($aids as $aid){
            $group_activity_mod->cancelActivity($aid,$gid);
        }
        $this->redis->del(REDIS_PREFIX."GroupActivity_".$gid);
        $this->redis->del(REDIS_PREFIX."ActFlag");
        
        echo "=======end=======";
    }
    
    //创建活动
    public function docreateActNotice(){
        echo '=======start=======';
        if(intval($this->redis->get(REDIS_PREFIX."ActFlag")) == 1){
            return;
        }
        
        $aid = $this->redis->rpop(REDIS_PREFIX.'NewAct');
        if(!$aid){
            return;
        }
        $actInfo = $this->load("groupActivity")->getActByAid($aid);
        if(!empty($actInfo)){
            $this->redis->set(REDIS_PREFIX."ActFlag",1);
            $group_mod = $this->load('group');
            $members = $group_mod->getGroupMember($actInfo['gid']);
            $group_mod->sendMessage($members,$actInfo['gid'],'G21',0,$actInfo['aid']);
            
            $this->redis->del(REDIS_PREFIX."ActFlag");
        }
        echo "=======end=======";
    }

    //活动即将开始
    public function dogoAct(){
        $time = time() + 7200;
        $etime = $time + 60;
        $data = $this->db->getAll("select aid,title,gid,type,stime,etime from r_group_activity where status=0 and stime <= $etime and stime >= $time");
        echo "======start======";
        foreach($data as $info){
            $this->redis->zrem(REDIS_PREFIX."ACTRecommend",$info['aid']);//即将开始的活动从活动推荐列表中移除
            //非官方活动
            if($info['type'] < 3){
                $members = $this->redis->smembers(REDIS_PREFIX."GAJoin_".$info['gid']."_".$info['aid']);
                $this->load('group')->sendMessage($members,$info['gid'],'G17',0,$info['aid']);
                $this->redis->zadd(REDIS_PREFIX."GroupActivity_".$info['gid'],$info['stime'],$info['aid']);
                //$this->redis->zadd(REDIS_PREFIX."GroupActivity",$info['stime'],$info['aid']);
                foreach($members as $uid){
                    $this->redis->zadd(REDIS_PREFIX."MYActivity_".$uid,$info['stime'],$info['aid']);
                }
            }else{
                $gids = $this->redis->smembers(REDIS_PREFIX."ACTaccept_".$info['aid']);
                foreach($gids as $gid){
                    $members = $this->redis->smembers(REDIS_PREFIX."GAJoin_".$gid."_".$info['aid']);
                    $this->load('group')->sendMessage($members,$gid,'G17',0,$info['aid']);
                    $this->redis->zadd(REDIS_PREFIX."GroupActivity_".$gid,$info['stime'],$info['aid']);
                    foreach($members as $uid){
                        $this->redis->zadd(REDIS_PREFIX."MYActivity_".$uid,$info['stime'],$info['aid']);
                    }
                }
            }
        }
        echo "======end======";
    }

    //活动结束
    public function doactOver(){
        echo "======start======";
        $time = time();
        $data = $this->db->getAll("select aid,title,gid,type,etime from r_group_activity where status=0 and etime<=$time");

        foreach($data as $info){
            if(in_array($info['type'],array(1,2,3,4))){//对竞赛类的活动发送消息
                $members = $this->redis->smembers(REDIS_PREFIX."GAJoin_".$info['gid']."_".$info['aid']);
                $this->load('group')->sendMessage($members,$info['gid'],'G18',0,$info['aid']);
            }
            $this->redis->zrem(REDIS_PREFIX."ACTRecommend",$info['aid']);//结束的活动从活动推荐列表中移除
            $this->db->query('update r_group_activity set status=2 where aid='.$info['aid']);
            $this->redis->hset(REDIS_PREFIX."ActivityInfo_".$info['aid'],'status',2);
            isset($info['gid']) && $this->redis->zadd(REDIS_PREFIX."GroupActivity_".$info['gid'],1,$info['aid']);
            $gids = $this->redis->smembers(REDIS_PREFIX."ACTaccept_".$info['aid']);
            $m = array();
            foreach($gids as $gid){
                $this->redis->zadd(REDIS_PREFIX."GroupActivity_".$gid,1,$info['aid']);
                $m = $this->redis->smembers(REDIS_PREFIX."GAJoin_".$gid."_".$info['aid']);
            }
            //$info['type'] < 3 && $this->redis->zadd(REDIS_PREFIX."GroupActivity",1,$info['aid']);
            $members = $this->redis->smembers(REDIS_PREFIX."GAJoin_".$info['gid']."_".$info['aid']);
            $members = array_merge($m,$members);
            foreach($members as $uid){
                $score = $info['etime'] - 473040000; //减15年
                $this->redis->zadd(REDIS_PREFIX."MYActivity_".$uid,$score,$info['aid']);
            }
        }
        echo "======end======";
    }

    //官方活动通知
    public function dogroupNotice(){
        echo '=======start=======';
        if(intval($this->redis->get(REDIS_PREFIX."ActFlag")) == 1){
            return;
        }
        
        $aid = $this->redis->rpop(REDIS_PREFIX.'OfficeAct');
        $actInfo = $this->load("groupActivity")->getActByAid($aid);
        if(!empty($actInfo)){
            $this->redis->set(REDIS_PREFIX."ActFlag",1);
            $groups = $this->db->getAll('select gid,uid from r_group where isDismiss=0');
            foreach($groups as $info){
                $content = "{$actInfo['title']} 开始啦,快来参加吧";
                $this->load('message')->insertMessage(5,175701,$info['gid'],$info['uid'],'InfoNtf',$content);
            }
            $this->redis->del(REDIS_PREFIX."ActFlag");
        }
        echo "=======end=======";
    }


    public function doasync(){
        set_time_limit(0);
        echo "=======start=======";
        $redisKey = REDIS_PREFIX."groupMileage";//群跑步总里程
        $sql = "select gid from r_group where isDismiss=0";
        $res = $this->db->getAll($sql);
        foreach($res as $info){
            $g = $this->redis->hget(REDIS_PREFIX.'GRTotal',$info['gid']);
            $this->redis->zadd($redisKey,$g,$info['gid']);
        }
        echo "=======end=======";
    }

    public function domygroup(){
        set_time_limit(0);
        echo "=======start=======";
        $sql = "select a.uid,a.gid from r_gmember a left join r_group b on a.gid=b.gid where b.isDismiss = 0 and a.role in(0,1,2)";
        $all = $this->db->getAll($sql);
        foreach($all as $info){
            if($this->load('group')->getGroupStatus($info['uid'],$info['gid']) == 0){
                $totalMileage = $this->load('group')->getTotalMileageByGid($info['gid']);
                $this->redis->zadd(REDIS_PREFIX."MGRankList_".$info['uid'],$totalMileage,$info['gid']);
            }

        }
        echo "=======end=======";
    }

    //异常跑步数据
    public function doexRundata(){
        set_time_limit(0);
        echo "==========start==========";
        //获取排行榜前1000名用户
        $users = $this->load('run')->getMileageStandingTopInfo(1000);
        foreach($users as $user){
            $uid = $user['uid'];
            $data = $this->db->getAll("select * from r_data where overSpeed = 0 and uid='$uid' and is_delete=0");
            foreach($data as $info){
                $overSpeed = $this->load('run')->checkCheatRun($uid,$info['mileage'],$info['elapsedtime'],$info['updatetime'],0);
                if($overSpeed){
                    $userInfo = $this->load('client')->getUserInfo($uid);
                    //标记当前的记录为异常
                    $this->db->query("update r_data1 set overSpeed = {$overSpeed} where did = {$info['did']}");
                    //更新用户数据
                    $addData = array(
                        'mileage' => -(round($info['mileage'], 3)),
                        'elapsedtime' => -(intval($info['elapsedtime'])),
                        'calorie' => -($info['calorie']),
                        'rate' => -1
                    );
                    $colArray = ['mileage','elapsedtime','calorie','rate'];
                    foreach($colArray as $name){
                        $colName = 'total_'.$name;
                        $value = $addData[$name];
                        if($this->db->update("update r_user set {$colName} = {$colName} + {$value} where uid = '{$uid}'") != false)
                        {
                            if($name == 'mileage')
                            {
                                $total_mileage = $this->db->getOne("select sum(mileage) from r_data where uid ='{$uid}' and is_delete = '0' and overSpeed=0");
                                $value = round($total_mileage, 2);
                                $this->redis->HSET(REDIS_PREFIX.'UserInfo_'.$uid, $colName, $value);
                            }
                            else
                            {
                                $this->redis->HINCRBY(REDIS_PREFIX.'UserInfo_'.$uid, $colName, $value);
                            }
                        }
                    }
                    //更新用户好友排行榜
                    $this->load('run')->updateUserFStandings($uid,0-$info['mileage'],$info['addtime']);
                    //更新用户跑步等级信息
                    $this->load('client')->getUserLevelInfo($uid, TRUE);
                    // 更新用户里程排名
                    $this->load('run')->setClientMileageStandingsRank($uid, round($userInfo['total_mileage'] - $info['mileage'], 3));
                    //删除勋章数据
                    if($info['medal'] != "[]" && $info['medal'] != ""){
                        $mids = json_decode($info['medal'],true);
                        foreach($mids as $mid){
                            $this->db->query("delete from r_medal_record where uid='{$uid}' and medal_id='{$mid}' limit 1");
                        }
                    }
                }
            }

        }
        echo "==========end==========";
    }

    //更新用户的总里程以及更新用户排行榜
    public function doupdateUser(){
        echo "======start======";
        $data = $this->db->getAll("select uid,sum(mileage) s from r_data where is_delete=0 and overspeed=0 group by uid");
        foreach($data as $item){
            $this->load('client')->setUserInfo($item['uid'],array('total_mileage'=>$item['s']));
            $this->redis->zadd(REDIS_PREFIX . 'StandingsMileage', $item['s'], $item['uid']);//更新用户里程
            $this->load('run')->updateMileageStandingsInfo(100);//更新用户排行榜
        }
        echo "======end======";
    }

    //补发勋章
    public function domedal(){
        set_time_limit(0);
        echo "========start======== \n";
        $time = strtotime(date("2017-02-17 00:00:00"));
        $etime = strtotime(date("2017-02-19 23:59:59"));
        $mileage = '5.00';
        $medal_id = '1057';
        $data = $this->db->getAll('select * from r_data where mileage >= '.$mileage.' and overspeed = 0 and updatetime >='.$time." and updatetime <= {$etime} group by uid order by addtime asc");
        $t = count($data);
        $i=0;
        foreach($data as $info){
            $medal = json_decode($info['medal'],true);
            $medalRecord = $this->db->getOne("select medal_id from r_medal_record where medal_id = {$medal_id} and uid={$info['uid']}");
            if(!in_array($medal_id,$medal) && !$medalRecord){
                $medal[] = $medal_id;
                $insertData = array('uid'=>$info['uid'],'medal_id'=>$medal_id,'add_time'=>$info['addtime'],'source_data'=>"20170219",'isCustom'=>1);
                $this->db->insertRowTable('r_medal_record',$insertData);
                $medal = json_encode($medal);
                $this->db->query("update r_data set medal='{$medal}' where did={$info['did']}");
            }
            $i++;
            echo "already done:".(round($i/$t,2)*100)."% \n";
        }
        echo "========done========"; 
    }
    
    public function doxxxx()
    {
        set_time_limit(0);
        ini_set('memory_limit','1024M');
        $beginTime  = 1463155200; //活动开始时间
        $endTime    = 1463328000; //活动结束时间
        $sourceDate = date('Ymd'); //发勋章日期
        $addTime    = time(); //勋章发放时间

        echo date('Y-m-d H:i:s') . ' | begin...' . "\n";

        $uids = $this->db->getCol('select gid,uid,count(1) num from r_gmember where gid in(11897,11915,31065,28821,13547,20781,30888,22222,27363,22224,26666,10497,14195,10566,31035,24112,23773,12506,29818,20936,10707,11303,20607,28235,23718,29654,13969,30885,10544,10892,11167,10435,22694,10431,11444,12692,10984,30510,20956,15676,12915,29344,28692,28593,30292,14880,30969,30647,30994,12081,28275,30966,28272,14835,29999,11897,23718,10984,14880) group by uid order by num desc');

        foreach($uids as $k => $uid)
        {
            $did = $this->db->getOne("select did from r_data where addtime between {$beginTime} and {$endTime} and overSpeed=0 and uid='{$uid}' and mileage>=1 limit 1");

            if($did)
            {
                $medalRecord = $this->db->getOne("select count(1) from r_medal_record where medal_id=1008 and uid={$uid}");

                if($medalRecord < 1)
                {
                    $medal[] = 1008;
                    $insertData = array('uid'=>$uid,'medal_id'=>1008,'add_time'=>$addTime,'source_data'=>$sourceDate,'isCustom'=>1);
                    $this->db->insertRowTable('r_medal_record',$insertData);
                    $medal = json_encode($medal);
                    $this->db->query("update r_data set medal='{$medal}' where did='{$did}'");
                }
            }

            echo date('Y-m-d H:i:s') . ' | putong:' . $k . "\n";
        }

        $uids = $this->db->getCol('select gid,uid,count(1) num from r_gmember where gid in(11897,23718,10984,14880) group by uid order by num desc');

        foreach($uids as $k => $uid)
        {
            $did = $this->db->getOne("select did from r_data where addtime between {$beginTime} and {$endTime} and overSpeed=0 and uid='{$uid}' and mileage>=1 limit 1");

            if($did)
            {
                $medalRecord = $this->db->getOne("select count(1) from r_medal_record where medal_id=1009 and uid={$uid}");

                if($medalRecord < 1)
                {
                    $medal[] = 1009;
                    $insertData = array('uid'=>$uid,'medal_id'=>1009,'add_time'=>$addTime,'source_data'=>$sourceDate,'isCustom'=>1);
                    $this->db->insertRowTable('r_medal_record',$insertData);
                    $medal = json_encode($medal);
                    $this->db->query("update r_data set medal='{$medal}' where did='{$did}'");
                }
            }

            echo date('Y-m-d H:i:s') . ' | leizhu:' . $k . "\n";
        }

        echo date('Y-m-d H:i:s') . ' | end.' . "\n";
    }
    
    //统计api访问和数据库，每小时运行一次
    public function docountApiVisitRecord(){
        set_time_limit(0);
        ini_set('memory_limit','1024M');
        echo "=======start======";
        echo time();
        $this->load('log')->countApiVisitRecord();
        echo "=======end========";
    }

    //一天运行一次
    public function docountApiVisitRecordOnce(){
        set_time_limit(0);
        ini_set('memory_limit','1024M');
        echo "=======start======";
        echo time();
        $this->load('log')->countApiVisitRecordOnce();
        //统计IM访问
        $this->load('log')->countIMRecord();
        echo "=======end========";
    }

    /*
     * 统计赛事成绩
     */
    public function dosaveMatchStatistics(){
        set_time_limit(0);
        ini_set('memory_limit','512M');
        echo "=======start======";
        echo time();
        $this->load('match')->saveStatistics();
        echo "=======end========";
    }

    /*
     * 同步数据库到搜索引擎
     */
    public function dosyncSearch(){
        set_time_limit(0);
        ini_set('memory_limit','1024M');
        echo "=======start======";
        echo time();
        $begin_time = time() - 24*3600;
        $start = 0;
        $limit = 1000;
        $i = 0;
        $search = $this->load('xunSearch')->init('news');
        $index = $search->getIndex();
        $index->openBuffer();
        while($rows = $this->db->getAll("SELECT `news_id`,`board`,`title`,`content`,`is_show`,`total_comment` FROM `r_news` WHERE add_time > $begin_time LIMIT $start,$limit")){
            foreach($rows as $row){
                $i++;
                $row['content'] = strip_tags($row['content']);
                $row['content'] = str_replace('#','刱',$row['content']);
                $row['title'] = str_replace('#','刱',$row['title']);
                $search->updateIndex($row);
            }
            $start += 1000;
        }
        $index->closeBuffer();
        echo "i: $i";
        echo "=======end========";
    }

    /**
     * 改变待验证群组7天未处理状态
     */
    public function dogroupStatus(){
        $time = time()-172800;
        echo "=======start====== \n";
        $groupData = $this->db->getAll("select id,gid,uid from r_group_add where status = 1 and addtime <= $time and isShow=1");
        $i=0;
        $c = count($groupData);
        foreach($groupData as $info){
            $this->db->query("update r_group_add set isShow=1,status=7 where id={$info['id']}");
            $i++;
            $fNum = round(($i/$c)*100,2);
            echo "已完成：{$fNum}% \n";
        }
        echo "=======end======";
    }

    /**
     * 同城群组数据
     */
    public function dogroupByCity(){
        echo "=======start====== \n";
        $groupData = $this->db->getAll("select province,gid,city from r_group where isDismiss=0");
        $i=0;
        $c = count($groupData);
        foreach($groupData as $group){
            $key = $this->load('group')->getCityKey($group['province'],$group['city']);
            !empty($key) && $this->redis->sadd($key,$group['gid']);
            $i++;
            $fNum = round(($i/$c)*100,2);
            echo "已完成：{$fNum}% \n";
        }
        echo "=======end======";

    }

    function dodealMedal(){
        echo "=======start======";
        $users = $this->load('run')->getMileageStandingTopInfo(1000);
        $i=0;
        $c = count($users);
        foreach($users as $user){
            $uid = $user['uid'];
            $five = $this->db->getRow("select five_time as value, updatetime from r_data where uid='{$uid}' and five_time > 930 and is_delete = 0 and overSpeed = 0 order by five_time ASC limit 1");
            $ten = $this->db->getRow("select ten_time as value, updatetime from r_data where uid='{$uid}' and ten_time > 1900 and is_delete = 0 and overSpeed = 0 order by ten_time ASC limit 1");
            $half = $this->db->getRow("select half_mtime as value, updatetime from r_data where uid='{$uid}' and half_mtime > 4200 and is_delete = 0 and overSpeed = 0 order by half_mtime ASC limit 1");
            $mara = $this->db->getRow("select mara_time as value, updatetime from r_data where uid='{$uid}' and mara_time > 8100 and is_delete = 0 and overSpeed = 0 order by mara_time ASC limit 1");
            if(empty($five)){
                $this->db->query("delete from r_medal_record where uid='{$uid}' and medal_id = 116");
            }
            if(empty($ten)){
                $this->db->query("delete from r_medal_record where uid='{$uid}' and medal_id = 117");
            }
            if(empty($half)){
                $this->db->query("delete from r_medal_record where uid='{$uid}' and medal_id = 118");
            }
            if(empty($mara)){
                $this->db->query("delete from r_medal_record where uid='{$uid}' and medal_id = 119");
            }
            $i++;
            $fNum = round(($i/$c)*100,2);
            echo "已完成：{$fNum}% \n";

        }
        echo "=======end======";
    }

    /**
     * 有道消息推送
     */
    public function dobbsPush(){
        echo date('Y-m-d H:i:s')."\t=======start======\t";

        $isPushing = $this->db->getOne("select news_id from r_news_push where status=1 limit 1");
        if($isPushing)
        {
            echo " | isPushing, break | \n";
        }
        else
        {
            $time = time();
            $row = $this->db->getRow("select news_id,gender,city,uids from r_news_push where status=0 and push_time<='{$time}' limit 1");
            $newsId = isset($row['news_id']) ? $row['news_id'] : 0;
            if($newsId > 0)
            {
                $this->db->update("update r_news_push set status=1 where news_id={$newsId}");
                $startUid = 0;
                $p = 1;

                $where = " 1 ";
                if($row['uids']){
                    $where .= " and u.uid IN ('".str_replace('|',"','",$row['uids'])."')";
                }else{
                    if($row['city']){
                        $where .= " and u.city='{$row['city']}'";
                    }
                    if($row['gender']){
                        $where .= " and u.gender='{$row['gender']}'";
                    }
                }
                while(TRUE)
                {
                    $listRow = 1000;
                    $uids = $this->db->getAll("select u.uid uid from r_user u left join r_client c on u.lastcid=c.cid where u.uid>{$startUid} and {$where} and c.version>=2800 order by u.uid asc limit {$listRow}");

                    if(!$uids)
                    {
                        break;
                    }

                    foreach($uids as $info)
                    {
                        $uid = $info['uid'];
                        $startUid = $uid;

                        echo date('H:i:s') . ' | LastUid: ' . $p . '/' . $startUid . "\n";

                        $contentArr = array(
                            "news_id" => $newsId,
                            "comment_id" => 0,
                            "content" => 0,
                            "gid" => 0
                        );
                        $content = json_encode($contentArr);
                        $this->load('message')->insertMessage(6,'S10006',0,$uid,'N9',$content);
                    }

                    $p++;
                }

                $time = time();
                $this->db->query("update r_news_push set status=2,push_time='$time' where news_id='$newsId'");
            }
        }

        echo "=======end======\n";
    }

    /*
     * 所有扑妞发的问答
     */
    public function doPuniuPostSync(){
        $redisKey = REDIS_PREFIX.'PuniuPostList';
        $add_time = $this->redis->exists($redisKey) ?  time()-7*24*3600 : 583257600;
        $sql = "SELECT DISTINCT r_boardpost.news_id FROM r_boardpost LEFT JOIN r_news ON r_news.news_id = r_boardpost.news_id
                WHERE r_news.uid = 175701 AND r_boardpost.boardId IN('healthy','injury','beginner','training')
                AND r_boardpost.isOn = 1 AND r_news.is_show = 1 AND r_news.is_best=1 AND r_news.add_time >= $add_time";
        
        $ids = $this->db->getAll($sql);
        foreach($ids as $row){
            $this->redis->sadd($redisKey,$row['news_id']);
        }
    }
    
    /*
     * 统计指定时间段（默认前四周）周跑人数及周跑2公里人数
     */
    public function doweekRunNum()
    {
        if (common::request('doExport', 'P')) {
            set_time_limit(0);
            ini_set('date.timezone','Asia/Shanghai');

            $dayweek                        = date('N'); //周几  
            $title                          = '周跑人数统计';
            $dataArr                        = [];
            $starttime                      = common::request('starttime', 'P');
            $endtime                        = common::request('endtime', 'P');
            $excelstr                       = '';
            $dataArr['weekNum']['title']    = '每周周跑人数';
            $dataArr['mileNum']['title']    = '每周两公里周跑人数';
            $gids                           = common::request('groupID', 'P');

            if (empty($starttime) || empty($endtime)) {
                //计算开始结束时间
                switch($dayweek)
                {
                    case 1:
                        $endtime    = strtotime(date('Ymd'));
                        break;
                    case 2:
                        $endtime    = strtotime(date('Ymd') - 1);
                        break;
                    case 3:
                        $endtime    = strtotime(date('Ymd') - 2);
                        break;
                    case 4:
                        $endtime    = strtotime(date('Ymd') - 3);
                        break;
                    case 5:
                        $endtime    = strtotime(date('Ymd') - 4);
                        break;
                    case 6:
                        $endtime    = strtotime(date('Ymd') - 5);
                        break;
                    case 7:
                        $endtime    = strtotime(date('Ymd') - 6);
                        break;
                }

                $starttime  = strtotime('-28 day', $endtime);
                $endtime--;
            } else {
                $starttime = strtotime($starttime);
                $endtime = strtotime($endtime);
            }
            
            $title      = '第' . date('W', $starttime) . '-' . date('W', $endtime) . $title;
            
            if (empty($gids)) {
                //周跑人数
                $dataArr['weekNum']['data'] = $this->db->getAll(
                    'SELECT count(DISTINCT(uid)) num ,FROM_UNIXTIME(addtime, "第%u周") wk from r_data where addtime BETWEEN ' . $starttime . ' and ' . $endtime . ' GROUP BY wk'
                );

                //两公里以上（包含）周跑人数
                $dataArr['mileNum']['data'] = $this->db->getAll(
                    'SELECT count(DISTINCT(uid)) num,FROM_UNIXTIME(addtime, "第%u周") wk from r_data where addtime BETWEEN ' . $starttime . ' and ' . $endtime . ' and mileage >=2 GROUP BY wk'
                );

                //excel表格
                foreach ($dataArr as $data)
                {
                    $excelstr .= '<table border="1">';
                    $excelstr .= '<tr><td colspan="2" align="center">' . $data['title'] . '</td></tr>';
                    $excelstr .= '<tr><td align="center">周</td><td align="center">人数</td></tr>';

                    foreach ($data['data'] as $key => $ret)
                    {    
                        $excelstr .= '<tr><td align="center">' . $ret['wk'] . '</td><td align="center">' . $ret['num'] . '</td></tr>'; 
                    }

                    $excelstr .= '</table><br /><br />';
                }
            } else {
                $sqlAll = <<<TSQL
                        SELECT
                            count(DISTINCT(d.uid)) num,
                            FROM_UNIXTIME(d.addtime, "第%u周") wk,
                            g.gid
                        FROM
                            r_data d
                        INNER JOIN r_gmember g ON d.uid = g.uid
                        WHERE
                            d.addtime BETWEEN $starttime
                        AND $endtime
                        AND g.gid IN ($gids)
                        GROUP BY
                            g.gid,
                            wk
TSQL;
                
                //周跑人数
                $dataArr['weekNum']['data'] = $this->db->getAll($sqlAll);

                $sqlTwoMile = <<<TSQL
                        SELECT
                            count(DISTINCT(d.uid)) num,
                            FROM_UNIXTIME(d.addtime, "第%u周") wk,
                            g.gid
                        FROM
                            r_data d
                        INNER JOIN r_gmember g ON d.uid = g.uid
                        WHERE
                            d.addtime BETWEEN $starttime
                        AND $endtime
                        AND d.mileage >= 2
                        AND g.gid IN ($gids)
                        GROUP BY
                            g.gid,
                            wk
TSQL;
                
                //两公里以上（包含）周跑人数
                $dataArr['mileNum']['data'] = $this->db->getAll($sqlTwoMile);

                //excel表格
                foreach ($dataArr as $data)
                {
                    $excelstr .= '<table border="1">';
                    $excelstr .= '<tr><td colspan="3" align="center">' . $data['title'] . '</td></tr>';
                    $excelstr .= '<tr><td align="center">周</td><td align="center">人数</td><td align="center">跑团ID</td></tr>';

                    foreach ($data['data'] as $key => $ret)
                    {    
                        $excelstr .= '<tr><td align="center">' . $ret['wk'] . '</td><td align="center">' . $ret['num'] . '</td><td align="center">' . $ret['gid'] . '</td></tr>'; 
                    }

                    $excelstr .= '</table><br /><br />';
                }
            }

            //处理ie中文标题乱码
            if(preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {  
                $title = str_replace('+','%20',urlencode($title));  
            } 

            header("Content-type:application/vnd.ms-excel;charset=UTF-8"); 
            header("Content-Disposition:attachment; filename=$title.xls");
            echo iconv("UTF-8", "GBK", $excelstr);
            exit;
        } else {
            $this->view->display('weekRunNum');
        }
    }
    public function dogetData(){
        $totalDay = 31;
        for($i=1;$i<$totalDay;$i++){
            $stime = strtotime(date("Y-m-{$i} 00:00:00"));
            $etime = strtotime(date("Y-m-{$i} 23:59:59"));
            $data = $this->db->getAll("select sum(mileage) s from r_data where updatetime >= {$stime} and updatetime <= {$etime} group by uid having s >=4 and s<= 6");
            $c = $this->db->getOne("select count(1) from r_data where updatetime >= {$stime} and updatetime <= {$etime}");
            $p = count($data);
            $s = 0;
            foreach($data as $val){
                $s += $val['s'];
            }
            echo date("Y-m-{$i}")."统计如下：\n";
            echo "跑步总记录数：".$s."\t跑步总人数：".$p."\t总次数为：{$c}\n";
        }
    }
    
    public function dopuNiuGroupInfo() {
        $rets = $this->db->getAll(
                "SELECT gid,`name`,FROM_UNIXTIME(addtime,'%Y年%m月%d日 %H:%i:%s') dt,members from r_group where gid in (SELECT gid from r_gmember where uid=175701)"
        );
        $tbStr = '<table>'.
                '<tr><td align="center">ID</td><td align="center">群组名</td><td align="center">创建时间</td><td align="center">成员数</td></tr>';
        
        foreach ($rets as $ret) {
            $tbStr .= '<tr><td align="center">' . $ret['gid'] . '</td>'
                    . '<td align="center">' . $ret['name'] . '</td>'
                    . '<td align="center">' . $ret['dt'] . '</td>'
                    . '<td align="center">' . $ret['members'] . '</td></tr>'; 
        }
        
        $tbStr .= '</table>';
        echo $tbStr;exit;
    }
    
    /**
     * 获取某天的注册用户发帖、跑步及一些基本信息
     */
    public function dodayRegisterInfo() {
        $dateTime = common::request('date', 'G');
        empty($dateTime) && $dateTime = date('Ymd', strtotime('-1 day'));
        $startTime  = strtotime($dateTime);
        $endTime    = $startTime + 86399; 
        $users =$this->db->getAll(
            'select uid,nickname,qq,sina,weixin,renren,phone from r_user where addtime between ' . $startTime . ' and ' . $endTime
        );
        $userInfo = [];
                
        if (!empty($users)) {
            foreach ($users as $k => $u) {
                $userInfo[$k]['nickname']   = $u['nickname'];
                $userInfo[$k]['qq']         = $u['qq'] ? '已绑定' : '未绑定';
                $userInfo[$k]['sina']       = $u['sina'] ? '已绑定' : '未绑定';
                $userInfo[$k]['weixin']     = $u['weixin'] ? '已绑定' : '未绑定';
                $userInfo[$k]['renren']     = $u['renren'] ? '已绑定' : '未绑定';
                $userInfo[$k]['phone']      = $u['phone'] ? '已绑定' : '未绑定';
                //查询发帖记录
                $ret = $this->db->getRow(
                    'SELECT count(1) num,max(real_addtime) mtime from r_news where uid=' . $u['uid']
                );
                $userInfo[$k]['postCount']  = $ret['num'];
                $userInfo[$k]['postTime']   = !empty($ret['mtime']) ? date('Y-m-d H:i:s', $ret['mtime']) : ''; 

                //查询跑步记录
                $ret = $this->db->getRow(
                    'SELECT count(1) num, max(addtime) mtime from r_data where uid=' . $u['uid']
                );
                $userInfo[$k]['runCount']  = $ret['num'];
                $userInfo[$k]['runTime']   = !empty($ret['mtime']) ? date('Y-m-d H:i:s', $ret['mtime']) : ''; 
            }
        }
        $tbStr = '未查到数据';
        
        if (!empty($userInfo)) {
            $tbStr = '<table border="1">'
                . '<tr><td align="center">昵称</td><td align="center">qq</td><td align="center">新浪</td><td align="center">微信</td>'
                . '<td align="center">人人</td><td align="center">手机</td><td align="center">发帖数</td><td align="center">最后一次发帖时间</td>'
                . '<td align="center">跑步次数</td><td align="center">最后一条跑步记录时间</td></tr>';
            
            foreach ($userInfo as $u) {
                $tbStr .= '<tr><td align="center">' . $u['nickname'] . '</td><td align="center">' . $u['qq']
                    . '</td><td align="center">' . $u['sina'] . '</td><td align="center">' . $u['weixin'] . '</td>'
                    . '<td align="center">' . $u['renren'] . '</td><td align="center">' . $u['phone'] 
                    . '</td><td align="center">' . $u['postCount'] . '</td><td align="center">' . $u['postTime'] . '</td>'
                    . '<td align="center">' . $u['runCount'] . '</td><td align="center">' . $u['runTime'] . '</td></tr>';
            }
            
            $tbStr .= '</table>';
        }
        
        echo $tbStr;
        exit;
    }
    
    public function docountGroupGeneral(){
        set_time_limit(600);
        ini_set('memory_limit','1024M');
        echo "======start======";
        echo time();
        $groupInfo = $this->db->getAll("select * from r_group where isDismiss = 0");
        
        foreach($groupInfo as $group){
            $sql = "select count(*) from r_group_news where gid = {$group['gid']}";
            $count = $this->db->getOne($sql);
            !$count && $count = 0;
            $redisKey = REDIS_PREFIX.'groupBypost';
            $this->redis->zadd($redisKey,$count,$group['gid']);
            
            $sql = "select sum(mileage) from r_group_run where gid = {$group['gid']}";
            $count = $this->db->getOne($sql);
            !$count && $count = 0;
            $redisKey = REDIS_PREFIX.'groupBymileage';
            $this->redis->zadd($redisKey,$count,$group['gid']);
            
            $sql = "select count(*) from r_group_activity where gid = {$group['gid']}";
            $count = $this->db->getOne($sql);
            !$count && $count = 0;
            $redisKey = REDIS_PREFIX.'groupByactivity';
            $this->redis->zadd($redisKey,$count,$group['gid']);
        }
        echo "======end======";
    }
    
    public function doRunUserCount() {
        $sql = 'SELECT
                    DISTINCT(uid)
                FROM
                    r_gmember
                WHERE
                    gid IN (
                        23497,
                        25460,
                        25472,
                        26695,
                        29362,
                        29380,
                        29626,
                        29763,
                        30014,
                        30304,
                        30441,
                        30581,
                        30684,
                        30686,
                        30952,
                        31336,
                        31568,
                        31569,
                        31624,
                        31625,
                        31626,
                        31627,
                        31628,
                        31629,
                        31630,
                        31631,
                        31632,
                        31633,
                        31634,
                        31653,
                        31654,
                        31655,
                        31656,
                        31657,
                        31658,
                        31659,
                        31660,
                        31661,
                        31667,
                        31668,
                        31669,
                        31670,
                        31671,
                        31672,
                        31673,
                        31680,
                        31681,
                        31682,
                        31683,
                        31684,
                        31685,
                        31686,
                        31687,
                        31688,
                        31692,
                        31693,
                        31694,
                        31695,
                        31696,
                        31698,
                        31699,
                        31700,
                        31701,
                        31702,
                        31703,
                        31704,
                        31705,
                        31707,
                        31708,
                        31709,
                        31710,
                        31711, 
                        31712,
                        31713
                    )
        AND role != 3';
        $uids = $this->db->getAll($sql);
        
        if (!empty($uids)) {
            $uidStr = '';

            foreach ($uids as $k => $uid) {
                if ($k == 0) {
                    $uidStr = $uid['uid'];
                } else {
                    $uidStr .= ',' . $uid['uid'];
                }
            }

            $sql = 'SELECT count(DISTINCT(uid)) from r_data where uid in ('.$uidStr.') and addtime BETWEEN 1464710400 and 1467302399 and overSpeed=0';;
            $count = $this->db->getCol($sql);
            echo $count[0];exit;
        } else {
            echo "no user";
            exit;
        }
    }
    
    /**
     * 统计客户端日常异常数
     */
    public function doClientDayExcepCount() {
        $this->in_logDb();
        $ret = $this->logDb->getCol('select count(1) from client_odd_statistics');
        $dayTime = date('G', time()) <= 1 ? strtotime(date('Ymd', time()) - 1) : strtotime(date('Ymd', time()));
        
        $datas = [];
        $isFirst = empty($ret['0']);
        //总数据统计
        $sql = $isFirst 
            ? 'select count(1) num,create_day,device_type,device_release from client_odd where order_id<>"" GROUP BY create_day,device_type,device_release'
            : 'select count(1) num,create_day,device_type,device_release from client_odd where create_day>='. $dayTime .' and order_id<>"" GROUP BY create_day,device_type,device_release';
        
        $ret = $this->logDb->getAll($sql);

        if (!empty($ret[0]['create_day'])) {
            foreach ($ret as $r) {
                $key = md5($r['create_day'] . $r['device_type'] . $r['device_release']);
                $datas[$key] = [
                    'date_time'         => $r['create_day'],
                    'total_num'         => $r['num'],
                    'device_type'       => $r['device_type'],
                    'device_release'    => $r['device_release'],
                    'except_num'        => 0
                ];
            }
        }

        //异常数据统计
        $sql = $isFirst
            ? 'select count(1) num,create_day,device_type,device_release from client_odd where order_id<>"" and (restart_sub_process_count > 1 or (restart_host_process_count > 0 and is_bress_quit=0)) GROUP BY create_day,device_type,device_release'
            : 'select count(1) num,create_day,device_type,device_release from client_odd where create_day>='. $dayTime .' and order_id<>"" and (restart_sub_process_count > 1 or (restart_host_process_count > 0 and is_bress_quit=0)) GROUP BY create_day,device_type,device_release';
        $ret = $this->logDb->getAll($sql);

        if (!empty($ret[0]['create_day'])) {
            foreach ($ret as $r) {
                $key = md5($r['create_day'] . $r['device_type'] . $r['device_release']);
                $datas[$key]['except_num'] = $r['num'];
            }
        }

        if (!empty($datas)) {
            echo 'total num: ' . count($datas) . '<br /><br />insert statistics datas please wait...<br /><br />';
            foreach ($datas as $d) {
                $this->logDb->insertRowTable('client_odd_statistics', $d);
            }
            exit('done');
        } else {
            exit('no datas');
        }
    }
    
    /**
     * 初始化马甲号跑步数据，单次
     */
    public function doinitVestData() {
        set_time_limit(0);
        $sUid = common::request('sUid', 'G', 0);
        //获取所有马甲号
        $vests = $this->_getVestUserInfo();
        
		if (!empty($vests)) {
			$timesMin = 10; //最小次数
			$timesMax = 20; //最大次数
			$milesMin = 100; 
			$milesMax = 200;
			$preDurat = 450; //每公里时长秒
			$preKal   = 60; //每公里卡路里消耗
            $client = uniqid();
            $medalIdArr = [100, 103, 112, 116 , 124, 125, 126];
            
            foreach ($vests as $k => $v) {
                if ($v['uid'] < $sUid) {
                    continue;   
                }
                
                $runTimes = mt_rand($timesMin, $timesMax);
                $tmpTimes = $runTimes;
                
                while($runTimes-- > 0) {
                    $timeStamp = time() - $runTimes * 86400;
                    $params['mileage'] = mt_rand(ceil($milesMin / $tmpTimes), floor($milesMax / $tmpTimes)) + round(mt_rand() / mt_getrandmax(), 2);
                    $params['elapsedtime'] = ceil($preDurat * $params['mileage']);
                    $params['calorie']  = ceil($preKal * $params['mileage']);
                    $params['order']    = date('YmdHis', $timeStamp);
                    $params['updatetime'] = $timeStamp;
                    $params['detail_speed'] = json_encode(["330.000000","328.000031","325.999969","310.000031","315.783020"]);
                    $signArr = $params;
                    //不参与sign加密
                    unset($signArr['detail_speed']);
                    $signArr['client'] = $client;
                    $signArr['time'] = $timeStamp;
                    $token = $v['uid'] . '-' . $timeStamp . '-' . md5($v['uid'].$timeStamp.'HUPUWANGLINZONGJINGLI***');
                    $signArr['token'] = $token;
                    ksort($signArr);
                    $sign = md5(http_build_query($signArr) . 'SHENGZHIJIAXINYINGQUBAIFUMEI***');
                    unset($signArr);
                    $url = 'http://' . $this->config['host'] . '/2/2.8.5/run/runningData?client=' . $client . '&time=' . $timeStamp . '&token=' . $token . '&sign=' . $sign;
                    $result = common::getContents($url, $params, 10, 'POST');
                    $apiRet = json_decode($result, true);
                    
                    if ($apiRet['status']['code'] != 200) {  //数据插入失败
//                        file_put_contents('/tmp/robotRunData.log', '第' . ($k + 1) . '个马甲号的第' . ($tmpTimes - $runTimes) . '跑步数据添加失败，api返回结果：' . $result . "\r\n", FILE_APPEND);
                        exit('occur error');
                    }
                    
                    sleep(1);
                }
                
                //发放用户勋章信息
                $timeStamp = time();
                $timeDate = date('Ymd', $timeStamp);
                
                foreach ($medalIdArr as $mk => $mid) {
                    $isExt = $this->db->getRowTable('r_medal_record', ['record_id'], 'uid=' . $v['uid'] . ' and medal_id=' . $mid);
                    
                    if (empty($isExt)) {
                        $inRet = $this->db->insertRow('r_medal_record', ['uid' => $v['uid'], 'medal_id' => $mid, 'add_time' => $timeStamp, 'source_data' => $timeDate], 1);
                        
                        if ($inRet === false) {
//                            file_put_contents('/tmp/robotRunData.log', '第' . ($k + 1) . '个马甲号勋章ID为' . $mid . '的勋章添加失败' . "\r\n", FILE_APPEND);
                            exit('occur error');
                        }
                    }
                }
            }
		}
        
        exit('done');
    }

    /**
     * 每周固定某天每个马甲号生成一条跑步数据，为保证上传数据的时间能随机至每一天，最好定周日更新数据
     */
    public function dovestPreweekData(){
        set_time_limit(0);
        //获取所有马甲号
        $vests = $this->_getVestUserInfo();
        
        if (!empty($vests)) {
            //随机小于当前时间且单周内任意一天6点到23点任意时间点
            $dayInWeek = date('N');
            
            foreach ($vests as $k => $v) {
                $upDateNum = mt_rand(1, $dayInWeek);
                $subSecs = ($dayInWeek - $upDateNum) * 86400;
                $upTime = strtotime(date('Ymd')) - $subSecs + 21600  + mt_rand(0, 1020) * 60;
                $client = uniqid();
                $timeStamp = time();
                $params['mileage'] = 4 + round(mt_rand() / mt_getrandmax(), 2);
                $params['elapsedtime'] = ceil(450 * $params['mileage']);
                $params['calorie']  = ceil(60 * $params['mileage']);
                $params['order']    = date('YmdHis', $timeStamp);
                $params['updatetime'] = $upTime > $timeStamp ? $timeStamp : $upTime;
                $params['detail_speed'] = json_encode(["330.000000","328.000031","325.999969","310.000031","315.783020"]);
                $signArr = $params;
                //不参与sign加密
                unset($signArr['detail_speed']);
                $signArr['client'] = $client;
                $signArr['time'] = $timeStamp;
                $token = $v['uid'] . '-' . $timeStamp . '-' . md5($v['uid'].$timeStamp.'HUPUWANGLINZONGJINGLI***');
                $signArr['token'] = $token;
                ksort($signArr);
                $sign = md5(http_build_query($signArr) . 'SHENGZHIJIAXINYINGQUBAIFUMEI***');
                unset($signArr);
                $url = 'http://' . $this->config['host'] . '/2/2.8.5/run/runningData?client=' . $client . '&time=' . $timeStamp . '&token=' . $token . '&sign=' . $sign;
                $result = common::getContents($url, $params, 10, 'POST');
                $apiRet = json_decode($result, true);

                if ($apiRet['status']['code'] != 200) {  //数据插入失败
//                    file_put_contents('/tmp/robotRunData.log', '第' . ($k + 1) . '个马甲号跑步数据添加失败，api返回结果：' . $result . "\r\n", FILE_APPEND);
                    exit('occur error');
                }

                sleep(1);   
            }  
        }
        
        exit('done');
    }
    
    /**
     * 马甲号自动点赞，发帖时间在30秒到5分钟以内,定时一分钟跑一次
     */
    public function dominuterVestLikePost() {
        //redisKey
        $reidsKey = REDIS_PREFIX .'minuterVestLikePost';
        $newsInfo = [];
        $nTime = time();
        
        if ($this->redis->exists($reidsKey)) {
            $newsArr = $this->redis->sMembers($reidsKey);
            sort($newsArr);
            $minNewsId = $newsArr[0];
            $newsInfo = $this->db->getAll('select news_id,add_time,loves from r_news where news_id>=' . $minNewsId . ' and add_time>' . ($nTime - 300) . ' and add_time<' . ($nTime - 30) . " and board!='[\"groupNews\"]'");
        } else {
            $newsInfo = $this->db->getAll('select news_id,add_time,loves from r_news where add_time>' . ($nTime - 300) . ' and add_time<' . ($nTime - 30) . " and board!='[\"groupNews\"]'");
        }
        
        if (!empty($newsInfo)) {
            //获取马甲号
            $vests = $this->_getVestUserInfo();
            $vestCount = count($vests);
            
            if(!empty($vests)) {
                $client = uniqid();
                
                foreach ($newsInfo as $nk => $nv) {
                    $timeStamp = time();
                    $canLike = false;
                    $likeVest = [];
                    $whileTimes = 0;
                    
                    //判断某个随机马甲号是否已赞过该帖
                    while(!$canLike) {
                        $sub = mt_rand(0, ($vestCount - 1));
                        if ($this->redis->ZSCORE(REDIS_PREFIX.'PostLikeList_'.$nv['news_id'], $vests[$sub]['uid']) === false || ++$whileTimes >= 10) { //限制次数防止死循环
                            $canLike = true;
                            $likeVest = $vests[$sub];
                        }
                    }
                    
                    $token = $likeVest['uid'] . '-' . $timeStamp . '-' . md5($likeVest['uid'].$timeStamp.'HUPUWANGLINZONGJINGLI***');
                    $signArr = [
                        'client'    => $client,
                        'time'      => $timeStamp,
                        'token'     => $token,
                        'news_id'   => $nv['news_id']
                    ];
                    ksort($signArr);
                    $sign = md5(http_build_query($signArr) . 'SHENGZHIJIAXINYINGQUBAIFUMEI***');
                    unset($signArr);
                    $url = 'http://' . $this->config['host'] . '/2/2.8.5/bbs/likePost?client=' . $client . '&time=' . $timeStamp . '&token=' . $token . '&sign=' . $sign . '&news_id=' . $nv['news_id'];
                    $result = common::getContents($url, [], 10, 'GET');
                    $apiRet = json_decode($result, true);

                    if ($apiRet['status']['code'] != 200) {  //数据插入失败
//                        file_put_contents('/tmp/robotLikePost.log', '马甲用户ID:' . $likeVest['uid'] . '为帖子ID' . $nv['news_id'] .'的帖子点赞失败，api返回结果：' . $result . "\r\n", FILE_APPEND);
                        exit('occur error');
                    }
                    
                    //清除key，重新添加
                    $nk == 0 && $this->redis->del($reidsKey);
                    $this->redis->sAdd($reidsKey, $nv['news_id']);
                    sleep(1);   
                }         
            }
        }
        
        exit('done');
    }
    
    /**
     * 马甲号自动点赞，发帖时间在24小时以内,定时一小时跑一次
     */
    public function dohourVestLikePost() {
        //redisKey
        $reidsKey = REDIS_PREFIX .'hourVestLikePost';
        $newsInfo = [];
        $nTime = time();
        
        if ($this->redis->exists($reidsKey)) {
            $newsArr = $this->redis->sMembers($reidsKey);
            sort($newsArr);
            $minNewsId = $newsArr[0];
            $newsInfo = $this->db->getAll('select news_id,add_time,loves from r_news where news_id>=' . $minNewsId . ' and add_time>' . ($nTime - 86400) . ' and add_time<' . ($nTime - 300) . " and board!='[\"groupNews\"]'");
        } else {
            $newsInfo = $this->db->getAll('select news_id,add_time,loves from r_news where add_time>' . ($nTime - 86400) . ' and add_time<' . ($nTime - 300) . " and board!='[\"groupNews\"]'");
        }
        
        if (!empty($newsInfo)) {
            //获取马甲号
            $vests = $this->_getVestUserInfo();
            
            if(!empty($vests)) {
                $client = uniqid();
                $vestUidArr = $newsLikeArr = [];

                foreach ($vests as $vv) {
                    $vestUidArr[] = $vv['uid']; 
                }
                
                foreach ($newsInfo as $nk => $nv) {
                    //计算本帖该次马甲号要赞次数
                    $likeLists = $this->redis->zRange(REDIS_PREFIX.'PostLikeList_'.$nv['news_id'], 0, 10000); //取出所有赞过用户ID
                    $vestLikeNum = count(array_intersect($likeLists, $vestUidArr)); //马甲号已赞次数
                    $runTimes = ($nv['loves'] - $vestLikeNum - floor($vestLikeNum / 4)) * 4;
                    $runTimes > 0 && $newsLikeArr[] = ['news_id' => $nv['news_id'], 'times' => $runTimes];
                }
                
                $this->redis->del($reidsKey);
                unset($newsArr, $minNewsId, $newsInfo, $nTime, $vestUidArr, $likeLists, $vestLikeNum, $runTimes);
                
                while (($nCount = count($newsLikeArr)) > 0) {
                    $subFlag = mt_rand(0, $nCount - 1);
                    $result = $this->_vestLikePost($vests, $newsLikeArr[$subFlag]['news_id'], $client);
                    $apiRet = json_decode($result, true);

                    if ($apiRet['status']['code'] != 200) {  //数据插入失败
//                        file_put_contents('/tmp/robotLikePost.log', '马甲号为帖子ID' . $newsLikeArr[$subFlag]['news_id'] .'的帖子点赞失败，api返回结果：' . $result . "\r\n", FILE_APPEND);
                        exit('occur error');
                    }
                    
                    $this->redis->sAdd($reidsKey, $newsLikeArr[$subFlag]['news_id']);
                    
                    //删除已达赞次数项
                    if (--$newsLikeArr[$subFlag]['times'] == 0) {
                        unset($newsLikeArr[$subFlag]);
                    }
                    
                    sleep(1);
                }
            }
        }
        
        exit('done');
    }
    
    /**
     * 马甲号自动点赞，发帖时间在120小时以内,定时12小时跑一次
     */
    public function dohalfDayVestLikePost() {
        //redisKey
        $reidsKey = REDIS_PREFIX .'halfDayVestLikePost';
        $newsInfo = [];
        $nTime = time();
        
        if ($this->redis->exists($reidsKey)) {
            $newsArr = $this->redis->sMembers($reidsKey);
            sort($newsArr);
            $minNewsId = $newsArr[0];
            $newsInfo = $this->db->getAll('select news_id,add_time,loves from r_news where news_id>=' . $minNewsId . ' and add_time>' . ($nTime - 86400 * 5) . ' and add_time<' . ($nTime - 86400) . " and board!='[\"groupNews\"]'");
        } else {
            $newsInfo = $this->db->getAll('select news_id,add_time,loves from r_news where add_time>' . ($nTime - 86400 * 5) . ' and add_time<' . ($nTime - 86400) . " and board!='[\"groupNews\"]'");
        }
        
        if (!empty($newsInfo)) {
            //获取马甲号
            $vests = $this->_getVestUserInfo();
            
            if(!empty($vests)) {
                $client = uniqid();
                $vestUidArr = $newsLikeArr = [];

                foreach ($vests as $vv) {
                    $vestUidArr[] = $vv['uid']; 
                }
                
                foreach ($newsInfo as $nk => $nv) {
                    //计算本帖该次马甲号要赞次数
                    $likeLists = $this->redis->zRange(REDIS_PREFIX.'PostLikeList_'.$nv['news_id'], 0, 10000); //取出所有赞过用户ID
                    $vestLikeNum = count(array_intersect($likeLists, $vestUidArr)); //马甲号已赞次数
                    $runTimes = ($nv['loves'] - $vestLikeNum - floor($vestLikeNum / 4)) * 4;
                    $runTimes > 0 && $newsLikeArr[] = ['news_id' => $nv['news_id'], 'times' => $runTimes];
                }
                
                $this->redis->del($reidsKey);
                unset($newsArr, $minNewsId, $newsInfo, $nTime, $vestUidArr, $likeLists, $vestLikeNum, $runTimes);
                
                while (($nCount = count($newsLikeArr)) > 0) {
                    $subFlag = mt_rand(0, $nCount - 1);
                    $result = $this->_vestLikePost($vests, $newsLikeArr[$subFlag]['news_id'], $client);
                    $apiRet = json_decode($result, true);

                    if ($apiRet['status']['code'] != 200) {  //数据插入失败
//                        file_put_contents('/tmp/robotLikePost.log', '马甲号为帖子ID' . $newsLikeArr[$subFlag]['news_id'] .'的帖子点赞失败，api返回结果：' . $result . "\r\n", FILE_APPEND);
                        exit('occur error');
                    }
                    
                    $this->redis->sAdd($reidsKey, $newsLikeArr[$subFlag]['news_id']);
                    
                    //删除已达赞次数项
                    if (--$newsLikeArr[$subFlag]['times'] == 0) {
                        unset($newsLikeArr[$subFlag]);
                    }
                    
                    sleep(1);
                }
            }
        }
        
        exit('done');
    }
    
    /**
     * 获取马甲号信息
     */
    private function _getVestUserInfo() {
        $redisKey = REDIS_PREFIX . 'vestUserInfo';
        $vests = $this->redis->get($redisKey);
        
        if (empty($vests)) {
            $vests = $this->db->getAll('select uid,addtime from r_user where is_robot=1');
            $this->redis->setex($redisKey, 86400, json_encode($vests));
        } else {
            $vests = json_decode($vests, true);
        }
        
        return $vests;
    }
    
    /**
     * 马甲号点赞
     * @param array $vests 马甲号信息
     * @param numeric $newsID 帖子ID
     * @param numeric $client 客户端唯一ID
     * @return json 点赞接口返回的json信息
     */
    private function _vestLikePost($vests, $newsId, $client) {
        $timeStamp = time();
        $canLike = false;
        $likeVest = [];
        $vestCount = count($vests);
        $whileTimes = 0;
        //判断某个随机马甲号是否已赞过该帖
        while(!$canLike) {
            $sub = mt_rand(0, ($vestCount - 1));
            if ($this->redis->ZSCORE(REDIS_PREFIX.'PostLikeList_'.$newsId, $vests[$sub]['uid']) === false || ++$whileTimes >= 10) {
                $canLike = true;
                $likeVest = $vests[$sub];
            }
        }

        $token = $likeVest['uid'] . '-' . $timeStamp . '-' . md5($likeVest['uid'].$timeStamp.'HUPUWANGLINZONGJINGLI***');
        $signArr = [
            'client'    => $client,
            'time'      => $timeStamp,
            'token'     => $token,
            'news_id'   => $newsId
        ];
        ksort($signArr);
        $sign = md5(http_build_query($signArr) . 'SHENGZHIJIAXINYINGQUBAIFUMEI***');
        unset($signArr);
        $url = 'http://' . $this->config['host'] . '/2/2.8.5/bbs/likePost?client=' . $client . '&time=' . $timeStamp . '&token=' . $token . '&sign=' . $sign . '&news_id=' . $newsId;
        return common::getContents($url, [], 10, 'GET');
    }
    
    /*
     * 机器人喜欢文章
     */
    public function dorobotLikePost(){
        exit;
        echo '==========start===========';
        set_time_limit(1800);
        $news_id = 4722760;
        $robotList = $this->db->getAll('select uid from r_user where is_robot = 1 limit 600');
        $bbs_mod = $this->load('bbs');
        shuffle($robotList);
        foreach($robotList as $row){
            $uid = $row['uid'];
            $record_id = $bbs_mod->likePost($news_id, $uid);
            $is_success = $record_id ? 1 : 0;
            if($is_success)
            {
                $this->redis->zadd(REDIS_PREFIX.'PostLikeList_'.$news_id, time(), $uid);
                $this->redis->zadd(REDIS_PREFIX.'MyLovePList_'.$uid, $record_id, $news_id);
                //$this->db->update("update r_news set loves = loves+1 where news_id = '{$news_id}'");
                $bbs_mod->update(['loves'=>'?+1','news_id'=>$news_id]);
                $this->redis->HINCRBY(REDIS_PREFIX. 'NewsInfo_'.$news_id, 'loves', 1);
            }
            echo $uid,' ';
            sleep(1);
        }
        echo '==========end===========';
    }

    /*
     * 机器人发表评论
     */
    public function dorobotComment(){
        exit;
        echo '==========start===========';
        set_time_limit(1800);
        $news_id = 4722760;
        $bbs_mod = $this->load('bbs');
        //评论内容
        $commentArr = array(
            0 => '跑了3个月都没发现，居然藏得这么深！',
            1 => '我擦，淘金币那个不错，一直做下去多好',
            2 => '还可以这样，晚上就试试',
            3 => '007你真棒！拿钱了分你1块！',
            4 => '淘金币那个安全不，有人试过吗？',
            5 => '淘金币怎么换钱？天猫吗？',
            6 => '给007点个赞，还是你好！',
            7 => '赞赞赞，正能量给你',
            8 => '看了这俩功能我都不敢说自己资深玩家',
            9 => '厉害了我的妞',
            10 => '方法已get，就差跑个步',
            11 => '连续下了好久的雨，好想试试啊',
            12 => '我曹这么好的功能咋没早发现！错过了几个亿',
            13 => '在哪里啊 没找到',
            14 => '楼上你按007说的步骤来就有啊',
            15 => '5个正能量！真棒！',
            16 => '咋没早点看到，生气！',
            17 => '今晚怒跑10km',
            18 => '扑妞么么哒~',
            19 => '好活动，好功能！支持！',
            20 => '决定今晚跑个步去',
            21 => '吼吼厉害了啊，马上试试',
            22 => '新版本才有是不是，等下升级',
            23 => '以前看到过，没在意，亏了',
            24 => '扑妞太爱你了么么哒',
            25 => '这个需要设置什么吗',
            26 => '给力，007好样的',
            27 => '万万没想到，还藏有这种功能啊',
            28 => '迫不及待走路也打开试试看',
            29 => '3能省2块是2块啊，就是这么节约',
            30 => '一举两得，开心',
            31 => '没想到你是这样的007！'
        );
        foreach ($commentArr as $key => $val) {
            $start = $key + 10;
            $robotUid = $this->db->getOne("select uid from r_user where is_robot = 1 order by addtime desc limit {$start},1");
            $bbs_mod->publishComment($news_id, $val, $robotUid);
            echo $robotUid,' ';
            sleep(1);
        }
        echo '==========end===========';
    }
    
    public function domakeCertificate(){
        set_time_limit(600);
        //ini_set('memory_limit','2048M');
        echo '========start=======';
        
        //群组活动证书
        $endTime = time() - 4500;
        $startTime = $endTime - 3600;
        //$startTime = 0;
        $activity_mod = $this->load('groupActivity');
        $res = $this->db->getAll("select aid from r_group_activity where etime > '$startTime' and etime <= '$endTime' order by etime asc");
        $aid = [];
        foreach($res as $row){
            $aid[] = $row['aid'];
        }
        if(!empty($aid)){
            $aid = implode(',',$aid);
            $data = $this->db->getAll("select * from r_activity_add where aid IN ($aid) order by field (aid,$aid)");
            foreach($data as $row){
                $_data = $activity_mod->getCertificateInfo($row['aid'],$row['gid'],$row['uid'],'update');
                if(empty($_data)){
                    continue;
                }
                $_row = [
                    'gid' => $row['gid'],
                    'aid' => $row['aid'],
                    'uid' => $row['uid'],
                    'nickname' => $_data['nickname'],
                    'header' => $_data['header'],
                    'mileage' => $_data['mileage'],
                    'farthest' => $_data['farthest'],
                    'total_elapsedtime' => $_data['total_elapsedtime'],
                    'max_speed' => $_data['max_speed'],
                    'day' => $_data['day'],
                    'groupName' => $_data['groupName'],
                    'isFinish' => $_data['isFinish'],
                    'rank' => $_data['rank'],
                    'cid' => $_data['cid'],
                    'img' => $_data['img'],
                    'addtime' => $_data['addtime'],
                    'act_type' => 0
                ];
                
                $this->db->updateRowTable('r_certificate',$_row);
                echo $_row['act_type'],',',$_row['aid'],',',$_row['uid'],"\n";
            }
        }
        
        //赛事证书
        //成绩统计时间为结束后1小时，证书录入时间为赛事结束1小时15分钟
        $match_mod = $this->load('match');
        $client_mod = $this->load('client');
        $res = $this->db->getAll("select match_id as aid from r_match where etime > '$startTime' and etime <= '$endTime' order by etime asc");
        $aid = [];
        foreach($res as $row){
            $aid[] = $row['aid'];
        }
        if(!empty($aid)){
            $aid = implode(',',$aid);
            $data = $this->db->getAll("select * from r_match_add where match_id IN ($aid) order by field (match_id,$aid)");
            foreach($data as $row){
                if(empty($row) || $row['dabiao']==0){
                    continue;
                }
                $matchInfo = $match_mod->getMatchInfo($row['match_id']);
                $userInfo = $client_mod->getUserInfo($row['uid']);
                $_row = [
                    'gid' => '0',
                    'aid' => $row['match_id'],
                    'uid' => $row['uid'],
                    'nickname' => isset($userInfo['cer_nickname']) ? $userInfo['cer_nickname'] : $userInfo['nickname'],
                    'header' => isset($userInfo['cer_header']) ? $userInfo['cer_header'] : $userInfo['header'],
                    'mileage' => $row['total_mileage'],
                    'farthest' => $row['best_mileage'],
                    'total_elapsedtime' => $row['total_elapsedtime'],
                    'max_speed' => '',
                    'day' => ceil(($matchInfo['etime'] - $matchInfo['stime'])/3600/24),
                    'groupName' => '',
                    'isFinish' => $row['dabiao'],
                    'rank' => '',
                    'cid' => '',
                    'img' => '',
                    'addtime' => $matchInfo['etime'],
                    'act_type' => 1
                ];
                
                $this->db->updateRowTable('r_certificate',$_row);
                echo $_row['act_type'],',',$_row['aid'],',',$_row['uid'],"\n";
            }
        }
        
        echo '==========end========';
    }
    
    public function domatchMakeCertificate(){
        set_time_limit(600);
        //ini_set('memory_limit','2048M');
        echo '========start=======';
        
        //成绩统计时间为结束后1小时，证书录入时间为赛事结束1小时15分钟
        $endTime = time()-4500;
        $startTime = $endTime - 4500;
        $startTime = 0;
        $match_mod = $this->load('match');
        $client_mod = $this->load('client');
        $res = $this->db->getAll("select match_id as aid from r_match where etime > '$startTime' and etime <= '$endTime' order by etime asc");
        $aid = [];
        foreach($res as $row){
            $aid[] = $row['aid'];
        }
        if(empty($aid)){
            return;
        }
        $aid = implode(',',$aid);
        $data = $this->db->getAll("select * from r_match_add where match_id IN ($aid) order by field (match_id,$aid)");
        foreach($data as $row){
            if(empty($row) || $row['dabiao']==0){
                continue;
            }
            $matchInfo = $match_mod->getMatchInfo($row['match_id']);
            $userInfo = $client_mod->getUserInfo($row['uid']);
            $_row = [
                'gid' => '0',
                'aid' => $row['match_id'],
                'uid' => $row['uid'],
                'nickname' => isset($userInfo['cer_nickname']) ? $userInfo['cer_nickname'] : $userInfo['nickname'],
                'header' => isset($userInfo['cer_header']) ? $userInfo['cer_header'] : $userInfo['header'],
                'mileage' => $row['total_mileage'],
                'farthest' => $row['best_mileage'],
                'total_elapsedtime' => $row['total_elapsedtime'],
                'max_speed' => '',
                'day' => ceil(($matchInfo['etime'] - $matchInfo['stime'])/3600/24),
                'groupName' => '',
                'isFinish' => $row['dabiao'],
                'rank' => '',
                'cid' => '',
                'img' => '',
                'addtime' => $matchInfo['etime'],
                'act_type' => 1
            ];
            
            $this->db->updateRowTable('r_certificate',$_row);
            echo $_row['act_type'],',',$_row['aid'],',',$_row['uid'],"\n";
        }
        
        echo '==========end========';
    }

    // 导出某区域内某地点的坐标数据
    public function doabcd()
    {
        $hkData = $this->db->getAll('select d.did,d.mileage,de.coordinate from r_data d left join r_data_ext de on de.did=d.did where d.did in(6236986,6235270,6235269,6235268,6235267,6235266,6234470,6229974,6229567,6228053,6227938,6226600,6224672,6219094,6218196,6218195,6217862,6216626,6216624,6216623,6215908,6215784,6215783,6215782,6215781,6215588,6214781,6214031,6213786,6213177,6213175,6213174,6211314,6211072,6211071,6211070,6208546,6204757,6202742,6200877,6197950,6196266,6194718,6191790,6190627,6189020,6189019,6188827,6187789,6186662,6183234,6181311,6181310,6179119,6178662,6178196,6177507,6176006,6173397,6170916,6170360,6170033,6170032,6165996,6160406,6160147,6159237,6154922,6149143,6148581,6141437,6139149,6139147,6139145,6139144,6139139,6139138,6139136,6139132,6139125,6138699,6109226,6106318,6105082,6099510,6099509,6099176,6099175,6097051,6093833,6093048,6092630,6091047,6089379,6082932,6078727,6069829,6068917,6067725,6067663)');

        $html = '<html><body><table><tr><td>ID</td><td>Mileage</td><td>Point</td></tr>';

        foreach($hkData as $k => $v)
        {
            $coordinate = @base64_decode($v['coordinate']);
            $uncompress = $coordinate ? @gzuncompress($coordinate) : FALSE;
            !$uncompress && $uncompress = @gzuncompress($v['coordinate']);
            $v['coordinate'] = !$uncompress ? $v['coordinate'] : stripslashes($uncompress);
            $v['coordinate'] = trim($v['coordinate'], '"');
            $v['coordinate'] = $v['coordinate'] ? json_decode($v['coordinate'], true) : array();
            $v['coordinate'] = json_encode($v['coordinate']);

            if($v['coordinate'] == 'null')
            {
                var_dump($z);
            }

            $html .= "<tr><td>{$v['did']}</td><td>{$v['mileage']}</td><td>{$v['coordinate']}</td></tr>";
        }

        $html .= '</table></body</html>';

        $runData = abs($coordinate['lat'], $coordinate['lng']);

        echo $html;
    }

    // 导出某区域内某地点的坐标数据
    public function doabc()
    {
        $dids = ['hk' => [], 'sj' => []];

        $didCounts = ['hk' => 0, 'sj' => 0];
        $page = 1;
        $count = 1000;

        $hk = [['lat' => 31.269107, 'lng' => 121.478633], ['lat' => 31.272794, 'lng' => 121.482946]];
        $sj = [['lat' => 31.207648, 'lng' => 121.539510], ['lat' => 31.224751, 'lng' => 121.563113]];

        echo date('H:i:s') . ' | Begin...' . "\n\n";

        while(1)
        {
            $begin = ($page - 1) * $count;

            echo date('H:i:s') . ' | Round: ' . $page . '/' . $begin . ' | hk: ' . $didCounts['hk'] . ' | sj: ' . $didCounts['sj'] . "\n";

            $runData = $this->db->getAll("select did,southWestPoint,northEastPoint from r_data where overSpeed=0 and mileage>3 order by did desc limit {$begin},{$count}");

            if($runData)
            {
                foreach($runData as $k => $v)
                {
                    $isHk = 0;
                    $isSj = 0;

                    $v['southWestPoint'] = json_decode($v['southWestPoint'], TRUE);
                    $v['northEastPoint'] = json_decode($v['northEastPoint'], TRUE);

                    $didCounts['hk'] < 100 && $isHk = $this->_gis($hk[0], $hk[1], $v['southWestPoint'], $v['northEastPoint']);
                    $didCounts['sj'] < 100 && $isSj = $this->_gis($sj[0], $sj[1], $v['southWestPoint'], $v['northEastPoint']);

                    if($isHk)
                    {
                        $dids['hk'][] = $v['did'];
                        $didCounts['hk'] ++;
                    }

                    if($isSj)
                    {
                        $dids['sj'][] = $v['did'];
                        $didCounts['sj'] ++;
                    }

                    if($didCounts['hk'] >= 99 && $didCounts['sj'] >= 99)
                    {
                        echo date('H:i:s') . ' | Ok - Full.' . "\n";
                        break;
                    }
                }

                print_r($dids);

                $page ++;
            }
            else
            {
                echo date('H:i:s') . ' | Ok - DataNone.' . "\n";
                break;
            }
        }

        common::pr($dids);
    }

    // 导出某区域内某地点的坐标数据
    public function _gis($boxLeftBottomPoint, $boxRightTopPoint, $searchLeftBottomPoint, $searchRightTopPoint)
    {
        $isInArea = FALSE;

        if(count($boxLeftBottomPoint) == 2 && count($boxRightTopPoint) == 2 && count($searchLeftBottomPoint) == 2 && count($searchRightTopPoint) == 2)
        {
            if($boxLeftBottomPoint['lat'] < $searchLeftBottomPoint['lat'] && $boxLeftBottomPoint['lng'] < $searchLeftBottomPoint['lng'] && $boxRightTopPoint['lat'] > $searchRightTopPoint['lat'] && $boxRightTopPoint['lng'] > $searchRightTopPoint['lng'])
            {
                $isInArea = TRUE;
            }
        }

        return $isInArea;
    }
    
    //自动订单过期失效
    public function docloseOrder(){
        $this->in_erpDb();
        $now = time();//24小时
        /*
        $sql = "update r_order set status=3 where status=1 AND pay_status='10' AND expireTime < $now";
        $this->erpDb->update($sql);
        */
        $rows = $this->erpDb->getAll("select id,goods from r_order where status=1 AND pay_status='10' AND expireTime < $now");
        $ids = [];
        $goods_mod = $this->load('goods');
        foreach($rows as $row){
            $goods = json_decode($row['goods']);
            if($goods){
                foreach($goods as $g){
                    $goods_mod->rollbackFlashGoodsSaleNum($g->id,$g->num);
                }
            }
            $ids[] = $row['id'];
        }
        if($ids){
            $sql = "update r_order set status=3 where id in('".implode("','",$ids)."')";
            $this->erpDb->update($sql);
        }
    }


    /**
     * cron 同步未开始闪购商品到提醒任务列表中,时间：未开始 前3分钟
     * 每分钟同步一次
     */
    public function dopushFlashGoodsToRemindList () {
        echo '--start--'.date('Y-m-d H:i:s').PHP_EOL;
        $this->load('flashBuy')->pushFlashGoodsToRemindList();
        echo '--end--'.date('Y-m-d H:i:s').PHP_EOL;exit;
    }

    /*
    * 消息推送 时间：未开始 前3分钟
    */
    public function dopushObjectMessage() {
        ini_set('memory_limit', '3096M');
        echo '--start--'.date('Y-m-d H:i:s').PHP_EOL;
        $sql = "select id,start_time from r_object_push where type = 1 and status = 5";
        $info = $this->db->getRow($sql);//待提醒
        if ($info) {
            if (bcsub(time(),$info['start_time']) > 10*600) {
                $this->update("update r_object_push set status= -10 where id= {$info['id']}");
                echo date('Y-m-d H:i:s').'10分钟超时取消推送'.PHP_EOL;
            }
            echo date('Y-m-d H:i:s'). 'id 为'.$info['id'].'的闪购推送正在进行中，退出脚本'.PHP_EOL;
            exit;
        }

        $sql = "select id from r_object_push where type = 1 and status = 0";
        $info = $this->db->getRow($sql);//待提醒
        if (!$info) {
            echo date('Y-m-d H:i:s').'push列表中没有需要提醒的闪购'.PHP_EOL;
            exit;
        }

        $startCronTime = time();
        $time = bcadd(time() , 3*60);
       $sql = "select rd.object_id,fs.title as fTitle from r_object_remind as rd
                  left join r_flash_sales as fs on rd.object_id=fs.id
                  where rd.status=0
                   and rd.type=1
                   and fs.status=0
                   and fs.start_time >= $startCronTime
                   and fs.start_time <=$time
                  limit 1";
        $remindInfo = $this ->db->getRow("$sql");
        if (!$remindInfo) {
            echo date('Y-m-d H:i:s').'暂时没有需要提醒的闪购（时间不在3分钟之内或其他）SQL:'.$sql.PHP_EOL;
            exit;
        }
        $list = $this->db->getAll("select id,object_id,cid,url,uid from r_object_remind where object_id={$remindInfo['object_id']} and type = 1 and status=0");
        if (!$list) {
            echo date('Y-m-d H:i:s').'ID为'.$info['id'].'的闪购商品，暂无用户设置提醒'.PHP_EOL;
            exit;
        }
        $flashBuyModel = $this->load('flashBuy');
        echo date('Y-m-d H:i:s').'ID为'.$info['id'].'的闪购商品状态变更：提醒中'.PHP_EOL;
        $flashBuyModel->saveRemindStatus($info['id'],5);
        $is_success = 0;
        foreach ($list as $key=>$val) {
            echo date('Y-m-d H:i:s').'ID为'.$val['id'].'的提醒项 开始提醒'.PHP_EOL;
            $val['title'] = $remindInfo['fTitle'];
            $r = $flashBuyModel->sendRemind(1,$val);
            if ($r) {
                $is_success++;
                echo date('Y-m-d H:i:s').'ID为'.$val['id'].'的提醒项 已经发送提醒'.PHP_EOL;
            } else  {
                echo date('Y-m-d H:i:s').'ID为'.$val['id'].'的提醒项 发送提醒失败！'.PHP_EOL;
            }
        }
        if ($is_success > 0) {
            $r = $flashBuyModel -> saveRemindStatus($info['id'],10);//已提醒
            if ($r) {
                echo date('Y-m-d H:i:s').'ID为'.$info['id'].'的闪购商品状态变更：已提醒'.PHP_EOL;
            }
        }
        echo date('Y-m-d H:i:s').'ID为'.$info['id'].'的闪购商品，成功提醒'.$is_success.'人';
    }

    /**
     * 闪购商品自动上下架
     */
    public function doautoFlashSalesShelf() {
        echo '--start--'.date('Y-m-d H:i:s').PHP_EOL;
        $this->load('flashBuy')->autoUpShelf();
        $this->load('flashBuy')->autoDownShelf();
        echo '--end--'.date('Y-m-d H:i:s').PHP_EOL;
    }
    
    /*
     * 更新好友排行
     */
    public function doupdateUserFStandings(){
        $did = common::request('did','P');
        $this->printResult = TRUE;
        if(empty($did)){
            $this->load('error')->getErrors(101);
            exit;
        }
        
        $run_mod = $this->load('run');
        $runData = $this->db->getRow('select * from r_data left join r_data_ext on r_data_ext.did=r_data.did where r_data.did='.$did.' limit 1');

        if($runData['is_delete'] != '0' || $runData['overSpeed'] > 0)
        {
            $this->result['result']['is_success'] = 1;
            return;
        }
        
        $uid = $runData['uid'];
        $run_mod->updateUserFStandings($uid, $runData['mileage']);
        
        $this->result['result']['is_success'] = 1;
    }
    
    /*
     * 更新最近跑步记录
     */
    public function doupdateLatestRunRecord(){
        $did = common::request('did','P');
        $this->printResult = TRUE;
        if(empty($did)){
            $this->load('error')->getErrors(101);
            exit;
        }
        
        $run_mod = $this->load('run');
        $runData = $this->db->getRow('select * from r_data left join r_data_ext on r_data_ext.did=r_data.did where r_data.did='.$did.' limit 1');
        
        if($runData['is_delete'] != '0' || $runData['overSpeed'] > 0)
        {
            $this->result['result']['is_success'] = 1;
            return;
        }
        
        $uid = $runData['uid'];
        $runRecord = array('mileage'        => $runData['mileage'],
                           'elapsedtime'    => $runData['elapsedtime'],
                           'city'           => $runData['city'],
                           'calorie'        => $runData['calorie'],
                           'updatetime'     => $runData['updatetime']
                           );
        $this->load('client')->getLatestRunRecord($uid, $runRecord);
        
        $this->result['result']['is_success'] = 1;
    }
    
    /*
     * 更新用户跑步等级信息
     */
    public function doupdateUserLevelInfo(){
        $did = common::request('did','P');
        $this->printResult = TRUE;
        if(empty($did)){
            $this->load('error')->getErrors(101);
            exit;
        }
        
        $run_mod = $this->load('run');
        $runData = $this->db->getRow('select * from r_data left join r_data_ext on r_data_ext.did=r_data.did where r_data.did='.$did.' limit 1');
        if($runData['is_delete'] != '0' || $runData['overSpeed'] > 0)
        {
            $this->result['result']['is_success'] = 1;
            return;
        }
        
        $uid = $runData['uid'];
        $this->load('client')->getUserLevelInfo($uid, TRUE);
        
        $this->result['result']['is_success'] = 1;
    }
    
    /*
     * 更新日跑步数据
     */
    public function doupdateDayRunData(){
        $did = common::request('did','P');
        $this->printResult = TRUE;
        if(empty($did)){
            $this->load('error')->getErrors(101);
            exit;
        }
        
        $run_mod = $this->load('run');
        $runData = $this->db->getRow('select * from r_data left join r_data_ext on r_data_ext.did=r_data.did where r_data.did='.$did.' limit 1');
        if($runData['is_delete'] != '0' || $runData['overSpeed'] > 0)
        {
            $this->result['result']['is_success'] = 1;
            return;
        }
        
        $uid = $runData['uid'];
        //日跑步
        $run_mod->updateDayRunData($uid, $runData['updatetime']);
        
        $this->result['result']['is_success'] = 1;
    }
    
    /**
     * 跑么杯状态变更
     */
    public function domodifyPmStatus() {
        echo '--start--'.date('Y-m-d H:i:s').PHP_EOL;
        $this->load('paome/cup')->autoModifyPaomeStatus();
        echo '--end--'.date('Y-m-d H:i:s').PHP_EOL;
    }

    /**
     * 跑么杯排名同步
     */
    public function doautoInitRank() {
        echo '--start--'.date('Y-m-d H:i:s').PHP_EOL;
        $this->load('paome/cup')->autoInitRank();
        echo '--end--'.date('Y-m-d H:i:s').PHP_EOL;
    }

    /**
     * 跑么杯机器人里程增加
     **/
    public function doPaomeRobotsRunData()
    {
        $h = intval(date('G'));

        if(!(($h >= 5 && $h <= 10) || ($h >= 15 && $h <= 23)))
        {
            echo date('Y-m-d H:i:s') . " | Out Time\n";
            exit;
        }

        echo date('Y-m-d H:i:s') . " | Begin\n";
        set_time_limit(0);

        $clubs = [];
        $overClubs = [];
        $vests = [];

        // 所有机器人战队
        $robots = $this->db->getAll('select club_id,uid from r_pm_club_users where club_id>=110 and club_id<=140 and status=0');
        foreach($robots as $k => $robot)
        {
            $clubs[$robot['club_id']][] = $robot['uid'];
        }

        // 当天已产生过记录的战队
        $robots = $this->db->getAll('select club_id,uid from r_pm_club_users_robot where day=' . date('Ymd'));
        if($robots)
        {
            foreach($robots as $k => $robot)
            {
                $overClubs[$robot['club_id']][] = $robot['uid'];
            }
        }

        foreach($clubs as $clubId => $uids)
        {
            if(!empty($overClubs[$clubId]))
            {
                $uids = array_diff($uids, $overClubs[$clubId]);
            }
            
            if(!empty($uids))
            {
                $uids = array_values($uids);
                $uid = $uids[array_rand($uids, 1)];

                if($uid)
                {
                    $vests[$clubId] = $uid;
                }
            }
        }
        
        if(!empty($vests))
        {
            foreach($vests as $clubId => $uid)
            {
                $upTime = strtotime(date('Ymd')) + rand(14400, 86000);
                $client = uniqid();
                $timeStamp = time();
                $params['mileage'] = rand(1, 10) + round(mt_rand() / mt_getrandmax(), 1);
                $params['elapsedtime'] = ceil(rand(600, 800) * $params['mileage']);
                $params['calorie']  = ceil(60 * $params['mileage']);
                $params['order']    = date('YmdHis', $timeStamp);
                $params['updatetime'] = $upTime > $timeStamp ? $timeStamp : $upTime;
                $params['detail_speed'] = json_encode(["530.000000","528.000031","525.999969","610.000031","615.783020"]);
                $signArr = $params;
                unset($signArr['detail_speed']);
                $signArr['client'] = $client;
                $signArr['time'] = $timeStamp;
                $token = $uid . '-' . $timeStamp . '-' . md5($uid.$timeStamp.'HUPUWANGLINZONGJINGLI***');
                $signArr['token'] = $token;
                ksort($signArr);
                $sign = md5(http_build_query($signArr) . 'SHENGZHIJIAXINYINGQUBAIFUMEI***');
                unset($signArr);
                $url = 'http://' . $this->config['host'] . '/2/2.8.5/run/runningData?client=' . $client . '&time=' . $timeStamp . '&token=' . $token . '&sign=' . $sign;
                $result = common::getContents($url, $params, 10, 'POST');
                $apiRet = json_decode($result, true);

                if($apiRet['status']['code'] != 200)
                {
                    echo date('Y-m-d H:i:s') . " | ApiError | ClubId:{$clubId} | Uid:{$uid}\n";
                    continue;
                }
                else
                {
                    $data = ['club_id' => $clubId, 'uid' => $uid, 'day' => date('Ymd'), 'create_time' => $this->time];
                    $this->db->insertRow('r_pm_club_users_robot', $data, 1);

                    echo date('Y-m-d H:i:s') . " | Success | ClubId:{$clubId} | Uid:{$uid}\n";
                }

                sleep(1);   
            }  
        }
        else
        {
            echo date('Y-m-d H:i:s') . " | Empty\n";
        }      

        echo date('Y-m-d H:i:s') . " | End\n\n";  
    }
    
    private function get_city_by_Lng_Lat($lat,$lng){
        $url = "http://api.map.baidu.com/geocoder/v2/?location=$lat,$lng&output=json&coordtype=gcj02ll&ak=x9hasHu3yWStXtGAYAc5HEhMZ0CvcLmd";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        $output = curl_exec($ch);
        curl_close($ch);
        $reslt = json_decode($output,true);
        if (!$reslt || $reslt['status'] <> 0) {
            echo '失败状态码:'.$reslt['status'].PHP_EOL;
            return 10000000 ;
        }
        $addressComponent = $reslt['result']['addressComponent'];
        $city = $addressComponent['city'];
        if (!$city) {
            $province = $addressComponent['province'];
            $city = $province;
        }
        return $city;
    }

    /**
     * 用户年度数据跑步城市生成
     */
    public function dogetUserRunCityCnt() {
        $startTime = strtotime(date('2016-01-01'));
        $endTime = strtotime(date('2017-01-01'));
//        $failDidCnt = $this->redis->sCard(REDIS_PREFIX .'2016YearAnalyzeUserCity');
//        if ($failDidCnt> 0) {
//            //$maxDid = $this->db->getOne("select did from user_run_did_list order by id desc limit 1");
//            echo date('Y-m-d H:i:s').'$failDidCnt >0'.PHP_EOL;
//            $failDid = $this->redis->sMembers(REDIS_PREFIX .'2016YearAnalyzeUserCity');
//            $strDid = implode(',', $failDid);
//            $arrPoint = $this->db->getAll("select did,uid,point_coordinate from r_data where uid> 0  and overSpeed = 0  and updatetime>=$startTime and updatetime<$endTime
//            and  did not in(select did from user_run_city_list) and did not in($strDid)  limit 5000");
//        } else {
//            echo date('Y-m-d H:i:s').'$failDidCnt =0'.PHP_EOL;
//            $arrPoint = $this->db->getAll("select did,uid,point_coordinate from r_data where uid> 0  and overSpeed = 0  and updatetime>=$startTime and updatetime<$endTime
//            and  did not in(select did from user_run_city_list) limit 5000");
//        }
        $arrPoint = $this->db->getAll("select * from user_run_did_list where status=0 limit 50000");
        if (!$arrPoint) {
            echo date('Y-m-d H:i:s').'已跑完'.PHP_EOL;
            return false;
        }
        echo date('Y-m-d H:i:s').'继续'.PHP_EOL;
        foreach ($arrPoint as $key=>$val) {
            $arr = $this->db->getRow("select did,uid,point_coordinate from r_data where did={$val['did']}");
            if(!$arr) {
                $this->redis->sAdd(REDIS_PREFIX .'2016YearAnalyzeUserCity', $val['did']);
                continue;
            }
            $val['point_coordinate'] = $arr['point_coordinate'];
            $val['uid'] = $arr['uid'];

            if (!$val['point_coordinate']) {
                $this->redis->sAdd(REDIS_PREFIX .'2016YearAnalyzeUserCity', $val['did']);
                continue;
            }
            $isDid = $this->db->getOne("select id from user_run_city_list where did={$val['did']} and flag=0");
            if ($isDid) {
                echo date('Y-m-d H:i:s').'重复DID'.$val['did'].PHP_EOL;
                $data = array(
                    'did'=>$val['did'],
                    'status'=>1
                );
                $insertStr = common::arrayToString($data);
                $r = $this->db->insert("insert HIGH_PRIORITY into user_run_did_list set {$insertStr} on duplicate key update {$insertStr}");
                continue;
            }
            //第一次打点坐标
            $allPoint = json_decode($val['point_coordinate'] , true);
            if (!$allPoint) {
                $this->redis->sAdd(REDIS_PREFIX .'2016YearAnalyzeUserCity', $val['did']);
                continue;
            }
            if (isset($allPoint[0]) && $allPoint[0] != null) {
                $fristPoint = $allPoint[0];
            } else if(isset($allPoint[1]) &&  $allPoint[1] != null) {
                $fristPoint = $allPoint[1];
            } else if(isset($allPoint[2]) &&  $allPoint[2] != null) {
                $fristPoint = $allPoint[2];
            }else if(isset($allPoint[3]) &&  $allPoint[3] != null) {
                $fristPoint = $allPoint[3];
            }else if(isset($allPoint[4]) &&  $allPoint[4] != null) {
                $fristPoint = $allPoint[4];
            }else if(isset($allPoint[5]) &&  $allPoint[5] != null) {
                $fristPoint = $allPoint[5];
            }else if(isset($allPoint[6]) &&  $allPoint[6] != null) {
                $fristPoint = $allPoint[6];
            }else if(isset($allPoint[7]) &&  $allPoint[7] != null) {
                $fristPoint = $allPoint[7];
            }else if(isset($allPoint[8]) &&  $allPoint[8] != null) {
                $fristPoint = $allPoint[8];
            }else if(isset($allPoint[9]) &&  $allPoint[9] != null) {
                $fristPoint = $allPoint[9];
            }else if(isset($allPoint[10]) &&  $allPoint[10] != null) {
                $fristPoint = $allPoint[10];
            }else if(isset($allPoint[11]) &&  $allPoint[11] != null) {
                $fristPoint = $allPoint[11];
            }else {
                $this->redis->sAdd(REDIS_PREFIX .'2016YearAnalyzeUserCity', $val['did']);
                $data = array(
                    'did'=>$val['did'],
                    'status'=>1
                );
                $insertStr = common::arrayToString($data);
                $r = $this->db->insert("insert HIGH_PRIORITY into user_run_did_list set {$insertStr} on duplicate key update {$insertStr}");

                echo date('Y-m-d H:i:s').'城市查询失败DID-B'.$val['did'].PHP_EOL;
                continue;
            }
            if (isset($fristPoint['lng'])) {
                $lng = $fristPoint['lng'];
                $lat = $fristPoint['lat'];
            } else if(isset($fristPoint['longitude'])) {
                $lng = $fristPoint['longitude'];
                $lat = $fristPoint['latitude'];
            } else {
                $this->redis->sAdd(REDIS_PREFIX .'2016YearAnalyzeUserCity', $val['did']);
                $data = array(
                    'did'=>$val['did'],
                    'status'=>1
                );
                $insertStr = common::arrayToString($data);
                $r = $this->db->insert("insert HIGH_PRIORITY into user_run_did_list set {$insertStr} on duplicate key update {$insertStr}");

                echo date('Y-m-d H:i:s').'城市查询失败DID-A'.$val['did'].PHP_EOL;
                continue;
            }

            //API
            $city = $this->get_city_by_Lng_Lat($lat,$lng);
            $flag = 0;
//            if ($city != 10000000 && !$city) {
//                echo date('Y-m-d H:i:s').'城市查询失败DID'.$val['did'].PHP_EOL;
//                $this->redis->sAdd(REDIS_PREFIX .'2016YearAnalyzeUserCity', $val['did']);
//                continue;
//            }
            if($city == 10000000 || !$city) {
                $flag =1;
                $city = '';
            }
            $year = date('Y',$startTime);
            $time =time();
            $data = array(
                'uid'=>$val['uid'],
                'city'=>$city,
                'date'=>$year,
                'create_time'=>$time,
                'did'=>$val['did'],
                'flag'=>$flag
            );
            $insertStr = common::arrayToString($data);
            $r = $this->db->insert("insert HIGH_PRIORITY into user_run_city_list set {$insertStr} on duplicate key update {$insertStr}");
            $data = array(
                'did'=>$val['did'],
                'status'=>1
            );
            $insertStr = common::arrayToString($data);
            $r = $this->db->insert("insert HIGH_PRIORITY into user_run_did_list set {$insertStr} on duplicate key update {$insertStr}");

            echo date('Y-m-d H:i:s').'更新成功DID'.$val['did'].'|'.var_export($r, true).PHP_EOL;
        }
    }

    /**
     * 用户年终总结 解决数据问题
     */
    public function dogetUserYearQues() {
        exit;
        $r = 1;
        if ($r) {
            exit;
            echo date('Y-m-d H:i:s').'开始->'.PHP_EOL;
            ini_set('memory_limit','2048M');
            $list = $this->db->getAll("select `did`,`uid` from user_run_city_list");
            $re = array(array(),array(),array(),array(),array());
            foreach ($list as $k=>$v) {
                $updatetime = $this->db->getOne("select updatetime from r_data where did={$v['did']}");
                if ($updatetime <=0) {
                    continue;
                }
                $hours = date('H', $updatetime);
                if($hours >=0 && $hours<4) {
                    if (!array_key_exists($v['uid'], $re[0])) {
                        $re[0][$v['uid']] = 1;
                    }
                } else if($hours >=4 && $hours<10) {
                    if (!array_key_exists($v['uid'], $re[1])) {
                        $re[1][$v['uid']] = 1;
                    }
                } else if($hours >=10 && $hours<16) {
                    if (!array_key_exists($v['uid'], $re[2])) {
                        $re[2][$v['uid']] = 1;
                    }
                } else if($hours >=16 && $hours<21) {
                    if (!array_key_exists($v['uid'], $re[3])) {
                        $re[3][$v['uid']] = 1;
                    }
                } else if($hours >=21 && $hours<24) {
                    if (!array_key_exists($v['uid'], $re[4])) {
                        $re[4][$v['uid']] = 1;
                    }
                }
            }
            echo date('Y-m-d H:i:s').'结束->'.PHP_EOL;
            var_dump($re).PHP_EOL;
        } else {
            $startTime = strtotime(date('2016-01-01'));
            $endTime = strtotime(date('2017-01-01'));
            $did = $this->db->getOne("select did from user_run_did_list order by did desc limit 1");
            if ($did >0 ) {
                $list = $this->db->getAll("select did,uid,point_coordinate from r_data where did > $did and LENGTH(point_coordinate)>5 and uid> 0 and overSpeed = 0  and updatetime>=$startTime and updatetime<$endTime
               order by did asc limit 50000");
            } else {
                $list = $this->db->getAll("select did,uid,point_coordinate from r_data where uid> 0  and LENGTH(point_coordinate)>5 and uid> 0 and overSpeed = 0  and updatetime>=$startTime and updatetime<$endTime
                order by did asc  limit 1000");
            }
            if(!$list){
                echo date('Y-m-d H:i:s').'跑完 DID->'.$did;exit;
            }
            foreach ($list as $k=>$v) {
                $data = array(
                    'did'=>$v['did']
                );
                $isExist= $this->db->getOne("select id from user_run_city_list where did ={$v['did']}");
                if ($isExist) {
                    $data['status'] = 1;
                }
                $insertStr = common::arrayToString($data);
                $r = $this->db->insert("insert HIGH_PRIORITY into user_run_did_list set {$insertStr} on duplicate key update {$insertStr}");
                echo date('Y-m-d H:i:s').'更新成功DID'.$v['did'].'|'.var_export($r, true).PHP_EOL;
            }
        }
    }
    
    /**
     * 更新装备索引
    */
    public function doupdateGearIndex(){
        $gearId = common::request("gearId", 'G', '');
        echo $this->load('gear')->updateIndex($gearId);
    }
    
    /*
     * 给游戏用户勋章
     */
    public function givePlayerMedal(){
        $medal_mod = $this->load('medal');
        $dateStr = date('Ymd');
        $game_mod = $this->load('game');
        //个人
        $redis_key = REDIS_PREFIX.'Game_Rank_User';
        $rows = $this->redis->zrevrange($redis_key,0,10);
        foreach($rows as $uid){
            $medal_mod->addUserMedal($uid,$medal_id,$dateStr);
        }
        //宠物
        $rows = $this->db->getAll("select points,id from r_game_monsters order by points desc limit 10");
        foreach($rows as $row){
            $monster = $game_mod->getMonsterInfo($row['id']);
            $uid = $monster['uid'];
            $medal_mod->addUserMedal($uid,$medal_id,$dateStr);
        }
        //探险
        $redis_key = REDIS_PREFIX.'Game_Rank_Explore';
        $rows = $this->redis->zrevrange($redis_key,0,10);
        foreach($rows as $uid){
            $medal_mod->addUserMedal($uid,$medal_id,$dateStr);
        }
    }

    /*
     * 游戏数据
     */
    public function dogameData(){
        //获取游戏时间
        $gameInit = $this->redis->get(REDIS_PREFIX . 'gameIsOpen');
        if(!$gameInit){
            exit;
        }
        $gameInit = json_decode($gameInit, true);
        $gameStart = $gameInit['start_time'];
        $gameEnd = $gameInit['end_time'];
        $date = date('Y-m-d');
        if($date < $gameStart || $date > $gameEnd){
            exit;
        }
        $gameData = array();
        $gameData['date'] = $date;
        $sql = "SELECT COUNT(uid) monsterCount FROM r_game_users where FROM_UNIXTIME(addtime,'%Y-%m-%d') = \"{$date}\"";
        $gameData['monsterCount'] = $this->db->getOne($sql);  //当天宠物领养人数

        $sql = "SELECT COUNT(uid) chapterCount FROM r_game_users where chapter = 17";
        $gameData['chapterCount'] = $this->db->getOne($sql);  //剧情完成人数

        $sql = "SELECT COUNT(id) careCount,COUNT(DISTINCT(from_openid)) careUserCount FROM r_game_care_record_wx where FROM_UNIXTIME(addtime,'%Y-%m-%d') = \"{$date}\"";
        $careArr = $this->db->getRow($sql);  
        $gameData['careCount'] = $careArr['careCount'];   //当天恢复次数(微信中)
        $gameData['careUserCount'] = $careArr['careUserCount'];   //当天恢复人数(微信中)

        $sql = "SELECT COUNT(id) poiCount,COUNT(DISTINCT(poi)) poiOnlyCount,COUNT(DISTINCT(uid)) poiUser FROM r_game_fight_record where FROM_UNIXTIME(addtime,'%Y-%m-%d') = \"{$date}\"";
        $careArr = $this->db->getRow($sql);  
        $gameData['poiCount'] = $careArr['poiCount'];   //poi探索次数
        $gameData['poiOnlyCount'] = $careArr['poiOnlyCount'];   //poi探索个数
        $gameData['poiUser'] = $careArr['poiUser'];   //poi探索人数

        $sql = "SELECT COUNT(id) failureCount FROM r_game_fight_record WHERE result = 0 and FROM_UNIXTIME(addtime,'%Y-%m-%d') = \"{$date}\"";
        $gameData['failureCount'] = $this->db->getOne($sql);  //战斗失败次数

        $sql = "SELECT COUNT(id) successCount FROM r_game_fight_record WHERE result = 1 and FROM_UNIXTIME(addtime,'%Y-%m-%d') = \"{$date}\"";
        $gameData['successCount'] = $this->db->getOne($sql);  //战斗成功次数

        $this->redis->hset(REDIS_PREFIX.'gameDataByDate', $date, json_encode($gameData));
    }

    /**
     * 微课状态变更
     */
    public function domodifyLiveStatus() {
        echo '--start--'.date('Y-m-d H:i:s').PHP_EOL;
        $this->load('live/live')->autoUpShelf();
        echo '--end--'.date('Y-m-d H:i:s').PHP_EOL;
    }

    # 恢复有道帖子列表
    public function doShowtimeNews()
    {
        exit;

        $sql = 'SELECT news_id,add_time,board,city FROM `r_news` where is_show=1';
        $news = $this->db->getAll($sql);
        
        foreach($news as $k => $v)
        {
            $newsId = $v['news_id'];
            $score = $v['add_time'];
            $boards = json_decode($v['board'], TRUE);
            $city = $v['city'];
            $key = 'HupuRun_BoardPostList';

            if($boards && is_array($boards))
            {
                foreach($boards as $bk => $bv)
                {
                    if($bv && $bv != 'groupNews')
                    {
                        $this->redis->zadd($key . $bv . '_New', $score, $newsId);
                        $city && $this->redis->zadd($key . $bv . '_Locale_' . md5($city), $score, $newsId);
                    }
                }
            }
        }
    }

    # 恢复群组帖子列表
    public function doGroupNews()
    {
        exit;

        $sql = 'SELECT * FROM `r_group_news` where is_show=1';
        $groupNews = $this->db->getAll($sql);

        foreach($groupNews as $k => $v)
        {
            $gid = $v['gid'];
            $newsId = $v['news_id'];
            $score = $v['addtime'];
            $this->redis->zadd('HupuRun_GroupNews_' . $gid, $score, $newsId);
        }
    }

    # 恢复好友列表
    public function doFriends()
    {
        exit;

        ini_set('memory_limit', '4096M');

        $uids = $this->db->getCol("select uid from r_user");

        foreach($uids as $k => $uid)
        {
            $this->load('friends')->createFriendListRedis($uid);
            echo $k . '_' . $uid . "\n";
        }
    }

    # 恢复群组权限
    public function doGroupRole()
    {
        exit;

        ini_set('memory_limit', '4096M');

        $gms = $this->db->getAll('select gid,uid,role from r_gmember');

        foreach($gms as $k => $gm)
        {
            $this->redis->hset(REDIS_PREFIX.'GroupRole_' . $gm['gid'], $gm['uid'], $gm['role']);
            echo $k . ' | ' . $gm['gid'] . '_' . $gm['uid'] . '_' . $gm['role'] . "\n";
        }
    }

    # 恢复群组群主
    public function doGroupHost()
    {
        exit;

        ini_set('memory_limit', '4096M');

        $groups = $this->db->getAll('select gid,uid from r_group where isDismiss=0');

        foreach($groups as $k => $group)
        {
            $this->redis->hset(REDIS_PREFIX.'GroupHost', $group['gid'], $group['uid']);
        }
    }

    # 恢复群组中我的活动
    public function doGroupActivity()
    {
        exit;

        ini_set('memory_limit', '4096M');

        $gas = $this->db->getAll('select aid,stime,status,etime from r_group_activity');
        $ctime = time();

        foreach($gas as $k => $ga)
        {
            //未开始
            $time = $ga['stime'];

            //结束
            if($ga['etime'] < $ctime && $ga['status'] == 0)
            {
                $time = 1;
            }

            //正在进行中
            if($ga['stime'] < $ctime && $ctime < $ga['etime'] && $ga['status'] == 0)
            {
                $time = $ga['stime'] + 1000000000;
            }

            //取消
            if($ga['status'] == 1)
            {
                $time = 0;
            }

            $uas = $this->db->getAll("select uid,gid,add_time from r_activity_add where aid='{$ga['aid']}'");

            if($uas)
            {
                foreach($uas as $uk => $ua)
                {
                    $this->redis->zadd(REDIS_PREFIX . 'MYActivity_' . $ua['uid'], $time, $ga['aid']);
                }   
            }
        }
    }
}